The code will only work correctly if there is a node tail in the list.
The algorithm works with the following logic
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 a tail guard is so we can make "next" be the "tail" node of the list. (Its data is null and it next is null.) Otherwise, "prev".next would still be pointing to something.
Here is a class that uses LinkedListNode. I should note that if you are applying for a position as a programmer, you should be able to do this mainly from memory. :-)
class LinkedList<E> { static class LinkedListNode<E> { E data; LinkedListNode<E> next; } 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>();
corsiKa
source share