Java Reference
In-Depth Information
Node a private inner class of the LinkedList class. Because none of the list
methods returns a Node object, it is safe to leave the instance variables public.
public class LinkedList
{
. . .
private class Node
{
public Object data;
public Node next;
}
}
The LinkedList class holds a reference first to the first node (or null , if the
list is completely empty).
public class LinkedList
{
public LinkedList()
{
first = null;
}
public Object getFirst()
{
if (first == null)
throw new NoSuchElementException();
return first.data;
}
. . .
private Node first;
}
Now let us turn to the addFirst method (see Figure 4 ). When a new node is added
to the list, it becomes the head of the list, and the node that was the old list head
becomes its next node:
public class LinkedList
{
. . .
public void addFirst(Object element)
{
Node newNode = new Node();
newNode.data = element;
Search WWH ::




Custom Search