If the list is empty, headPtr
contains
null
and traverse()
will immediately return to its caller.
Recall (yet again) the three aspects of a loop that work together:
p
must be set up correctly.while
statement must be correct.p
must be done correctly.If done correctly, traversal will work with an empty list, a one-node list, and will print the first and last nodes of a longer list.
Here is traverse()
public void traverse() { Node p = headPtr; while ( p != null ) { System.out.print( p + ", " ); p = p.getNext(); } }
Here is a non-empty list:
The node pointer p
advances through the list until it reaches the last one.
Will traverse()
print out the last Node
?