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(); = "node 1"; = new Node(); = "node 2"; = new Node(); = "node 3"; = null;
Node temp = top;
while (temp != null)
temp =;
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
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