Java Reference
In-Depth Information
Indicating the End of a Linked List
The last node in a linked list should have its link instance variable set to null . That way,
your code can check whether a node is the last node by checking whether its link instance
variable is equal to null .
An Empty List Is Indicated by null
Suppose the variable head is supposed to contain a reference to the first node in a linked
list. Linked lists usually start out empty. To indicate an empty linked list, give the variable
head the value null . This is traditional and works out nicely for many linked list manipulation
algorithms.
Before we go on to discuss how nodes are added and removed from a linked list,
let us suppose that the linked list already has a few nodes and that you want to write
out the contents of all the nodes to the screen. You can do this with the method
outputList ( Display 15.3 ), whose body is reproduced here:
traversing a
linked list
Node1 position = head;
while (position != null )
{
System.out.println(position.getItem( ) + " "
+ position.getCount( ));
position = position.getLink( );
}
The method uses a local variable named position that contains a reference to one
node. The variable position starts out with the same reference as the head instance
variable, so it starts out positioned at the first node. The position variable then has its
position moved from one node to the next with the assignment
position = position.getLink( );
This is illustrated in Display 15.4. To see that this assignment “moves” the position
variable to the next node, note that the position variable contains a reference to the
node pointed to by the position arrow in Display 15.4. So, position is a name for that
node, and position.link is a name for the link to the next node. The value of link is
produced with the accessor method getLink . Thus, a reference to the next node in the
linked list is position.getLink( ) . You “move” the position variable by giving it the
value of position.getLink( ) .
 
Search WWH ::




Custom Search