next up previous
Next: Printing the elements of Up: Unit 12 Previous: Deleting the first element

Accessing successive nodes of a list

To perform an operation on all elements of a list, we have to reach each element starting from the first one, by following the next references. One way of doing this is through iteration. The loop scheme to access all elements of a list whose first element is referenced by a variable lis is the following.

ListNode lis = ...
ListNode p = lis;
while (p != null) {
  process the node referenced by p
  p = p.next;
}

Note that we start the ``scan'' of the list by using p as a reference to the current node. We initialize p to the value of lis, and then, at each iteration of the loop, we advance p to the next node through the statement p = p.next. Note that this statement does not modify in any way the list itself.


next up previous
Next: Printing the elements of Up: Unit 12 Previous: Deleting the first element