Java Reference
In-Depth Information
Listing 5-29. Creating and iterating over a linked list of nodes
class Nodes
{
public static void main(String[] args)
{
Node top = new Node();
top.name = "node 1";
top.next = new Node();
top.next.name = "node 2";
top.next.next = new Node();
top.next.next.name = "node 3";
top.next.next.next = null;
Node temp = top;
while (temp != null)
{
System.out.println(temp.name);
temp = temp.next;
}
}
}
Listing5-29 demonstratesthecreationofa singly linked list (alistwhereeachnode
consistsofasinglelinkfield).Thefirst Node instanceispointedtobyreferencevari-
able top , which identifies the top of the list. Each subsequent node in this linked list
isreferencedfromitspredecessor's next field.Thefinal next fieldissetto null to
signifytheendofthelinkedlist.(Thisexplicitinitializationisunnecessarybecausethe
fielddefaultstothenullreferenceduringinstanceinitialization,butispresentforclar-
ity).
Figure 5-5 reveals this three-node linked list.
Figure 5-5. Reference variable top points to the first node in this three-node linked list.
Listing5-29 alsoshowsyouhowtotraversethissinglylinkedlistbyfollowingeach
Node object's next field.Priortothetraversal, top 'sreferenceisassignedtovariable
 
 
Search WWH ::




Custom Search