| |
Traversing a Linked List | page 6 of 9 |
To traverse a list means to start at one end and visit all the nodes, solving a problem along the way. In the case of method printList , the task is to print the value field from each node.
class SinglyLinkedList
{
...
public void printList()
{
ListNode temp = first; // start from the first node
while (temp != null)
{
System.out.print(temp.getValue() + " ");
temp = temp.getNext(); // go to next node
}
}
...
}
Because temp is an alias to first , we can use it to traverse the list without altering the reference to the start of the list. The ListNode variable, temp , will contain null when we are done.
Until temp equals null , the while loop will do two steps at each node; print the data field, then advance the temp reference.
The statement, temp = temp.getNext() , is a very important one as this is how we move to the next node.
Another common list traversal problem is counting the number of nodes in the list. The lab exercise will ask you to solve this problem.
|