2011-03-21 10 views
8

Perdone mi ignorancia, pero estoy empezando a preparar mi primera entrevista técnica y se encontró con esta pregunta y respuesta sobre el tema LinkedList¿Cuál es LinkedListNode en Java

Pregunta: Implementar un algoritmo para eliminar un nodo en el centro de una sola lista enlazada, teniendo en cuenta sólo el acceso a ese nodo

 
public static boolean deleteNode(LinkedListNode n) { 
if (n == null || n.next == null) { 
    return false; // Failure 
} 
LinkedListNode next = n.next; 
n.data = next.data; 
n.next = next.next; 
return true; 
} 

quiero empezar a jugar con el código (hacer cambios compilan prueba), pero no estoy seguro de cómo empezar a hacer esto en Java. No puedo encontrar la clase LinkedListNode en documentos Java.

Esto podría ser una pregunta muy tonta pero si alguien puede señalarme en la dirección correcta, lo agradecerá.

EDITAR

Gracias por las respuestas rápidas y útiles. Supongo que mi pregunta no fue muy clara. El algoritmo anterior fue proporcionado como una solución a esa pregunta. Quería saber cómo implementar eso en Java para poder jugar con el código.

gracias

Respuesta

13

El código solo funcionará correctamente si hay un nodo de cola en la lista.

El algoritmo trabaja con la siguiente lógica

When referring to the node to be deleted, call it "curr" 
When referring to the node before "curr", call it "prev" 
When referring to the node after "curr", call it "next" 

To effectively delete our node, "prev".next should point to "next" 
It currently points to "curr" 

Our problem is that we have no reference to "prev" 

We know "prev".next points to "curr" 

Since we cannot change the fact that "prev".next points to "curr", 
we must have "curr" gobble up "next" 

We make "curr"s data be "next"s data 
We make "curr"s next be "next"s next 

The reason this only works if there's a tail guard 
is so we can make "next" be the "tail" node of the 
list. (Its data is null and it's next is null.) Otherwise, 
"prev".next would still be pointing to something. 

Aquí hay una clase que utiliza LinkedListNode. Debo señalar que si estás postulando para un puesto como programador, deberías poder hacer esto básicamente desde la memoria. :-)

class LinkedList<E> { 

    static class LinkedListNode<E> { 
     E data; 
     LinkedListNode<E> next; 
    } 

    /** 
    * Not exactly the best object orientation, but we'll manage 
    */ 
    static <E> E deleteNode(LinkedListNode<E> node) { 
     if(node == null || node.next == null) return null; 

     E retval = node.data; 
     LinkedListNode<E> next = node.next; 
     node.data = next.data; 
     node.next = next.next; 
     return retval; 
    } 

    private LinkedListNode<E> head; 
    private LinkedListNode<E> tail; 

    public LinkedList() { 
     this.head = new LinkedListNode<E>(); 
     this.tail = new LinkedListNode<E>(); 
     head.next = tail; 
    } 

    public void addLast(E e) { 
     LinkedListNode<E> node = new LinkedListNode<E>(); // e and next are null 
     tail.data = e; 
     tail.next = node; 
     tail = node; 
    } 

    public void addFirst(E e) { 
     LinkedListNode<E> node = new LinkedListNode<E>(); // e and next are null; 
     node.next = head.next; 
     node.data = e; 
     head.next = node; 
    } 

    public E deleteFirst() { 
     LinkedListNode<E> first = head.next; 
     head.next = first.next; 
     return first.data; 
    } 

    public E deleteLast() { 
     // cannot do without iteration of the list! :-(
     throw new UnsupportedOperationException(); 
    } 

    public LinkedListNode<E> findFirst(E e) { 
     LinkedListNode<E> curr = head.next; 
     while(curr != null) { 
      if(curr.data != null && curr.data.equals(e)) return curr; 
      curr = curr.next; 
     } 
     return null; 
    } 

    public void print() { 
     LinkedListNode<E> curr = head.next; 
     while(curr.next != null) { 
      System.out.println(curr.data); 
      curr = curr.next; 
     } 
    } 


    public static void main(String[] args) { 
     LinkedList<String> list = new LinkedList<String>(); 
     list.addLast("Apple"); 
     list.addLast("Bear"); 
     list.addLast("Chair"); 
     list.addLast("Dirt"); 

     //list.print(); 

     LinkedListNode<String> bear = list.findFirst("Bear"); 
     deleteNode(bear); 

     list.print(); 
    } 

} 
+0

Muchas gracias por explicar claramente cómo funciona esto. Así que quería saber cómo implementaría esto en Java. – riamo

+0

@Riamo ¿qué quieres decir? Ya ha enumerado el código que implementa esto. – corsiKa

+0

@glowcoder - Gracias - ese código no funciona - como LinkedListNode no es una clase en java SDK – riamo

5

Esta clase es más probable una clase hipotética utilizado para este ejemplo Linked List cuestión.

+0

Sí, eso es lo que pensé. Entonces, ¿hay algún ejemplo simple para implementar este algoritmo en Java? – riamo

0

Su pregunta es un poco confusa. si desea una lógica para eliminar un nodo en una lista individualmente vinculada o si desea aprender y usar java LinkedlistNode.

si se encuentra en el segundo el siguiente enlace le ayudará a

LinkedListNodee

o si desea que la lógica

let P the pointer to the current node 
P->data = P->next->data 
Q=P->next 
P->next=Q->next 
delete(Q) 
0

Los detalles importantes en esta cuestión se refieren a estructuras de datos, Java es solo el lenguaje que se está utilizando para implementar en este caso.
Debe leer el artículo de wikipedia sobre linked lists, y para esta pregunta tenga cuidado de que su solución no produzca referencias colgantes o nodos huérfanos.
Realice algunas búsquedas en los dos términos en negrita y asegúrese de comprenderlas

6

LinkedListNode es una clase que definirá para contener datos.Para que funcione el ejemplo anterior, he escrito rápidamente este código (solo para hacerte entender el concepto simple) en el que estoy creando 3 nodos (que están vinculados entre sí) y luego borro el del medio llamando al deleteNode método que ha especificado en su pregunta.

El código es bastante auto explicativo. Déjeme saber si esto ayuda. Buena suerte

class LinkedListNode 
{ 
    public Object data; 
    public LinkedListNode next; 

    public LinkedListNode(Object data) { 
    this.data = data; 
    } 
} 

class DeleteNodeLinkedList 
{ 
    public static void main(String[] args) 
    { 
     LinkedListNode node_1 = new LinkedListNode("first");   
     LinkedListNode node_2 = new LinkedListNode("second"); 
     node_1.next = node_2; 
     LinkedListNode node_3 = new LinkedListNode("third"); 
     node_2.next = node_3; 

     System.out.println("*** Print contents of linked list"); 
     LinkedListNode current = node_1; 
     while (current != null) { 
      System.out.println(current.data); 
      current = current.next; 
     } 

     System.out.println("*** Now delete second node"); 
     deleteNode(node_2); 

     System.out.println("*** Print after deleting second node"); 
     current = node_1; 
     while (current != null) { 
      System.out.println(current.data); 
      current = current.next; 
     } 
    } 

    public static boolean deleteNode(LinkedListNode n) 
    { 
     if (n == null || n.next == null) { 
      return false; // Failure 
     } 
     LinkedListNode next = n.next; 
     n.data = next.data; 
     n.next = next.next; 
     return true; 
    } 
} 
+0

Gracias fue muy útil – riamo

Cuestiones relacionadas