When p
points to the last Node
,
the loop body will execute for the last time and print that node.
while ( p != null ) { System.out.print( p + ", " ); // print the node p = p.getNext(); // advance the pointer }
Then the pointer gets a copy of what is in the next
member
of that Node
.
But that is a null
so the loop will end.
It is easy to miss the last node, or to try to go too far. This is the pointer equivalent of the notorious off-by-one error.
How long may a linked list grow?