Java Reference
In-Depth Information
newNode.next = first;
first = newNode;
}
. . .
}
672
673
Figure 4
Adding a Node to the Head of a Linked List
Removing the first element of the list works as follows. The data of the first node are
saved and later returned as the method result. The successor of the first node becomes
the first node of the shorter list (see Figure 5 ). Then there are no further references to
the old node, and the garbage collector will eventually recycle it.
public class LinkedList
{
. . .
public Object removeFirst()
{
if (first == null)
throw new NoSuchElementException();
Object element = first.data;
first = first.next;
return element;
}
. . .
Search WWH ::




Custom Search