go to previous page   go to home page   go to next page highlighting

Answer:

If the list is empty, headPtr contains null and traverse() will immediately return to its caller.


Traverse Loop

Recall (yet again) the three aspects of a loop that work together:

  1. The initial value of p must be set up correctly.
  2. The condition in the while statement must be correct.
  3. The change in 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:

linked list traversal

The node pointer p advances through the list until it reaches the last one.


QUESTION 8:

Will traverse() print out the last Node?


go to previous page   go to home page   go to next page