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

Answer:

Of course.


Traverse

Following the links from start to finish is a traversal of the list.

Here is LinkedList again, now with a traverse() method. (As before, it prints and extra comma after the last node. You may wish to fix that with some extra logic.)

// LinkedList.java
//
public class LinkedList
{
   private Node headPtr = null;
  
  // The constructor creates an empty list
  public LinkedList()
  {
    headPtr = null;
  }

  // Determine if the List is empty
  public boolean isEmpty()
  {
     return headPtr == null;
  }
  
  // Insert one Node containing data at the head
  // of the list. 
  public void insertFirst( int data )
  {
    Node newFirst = new Node( data );
    newFirst.setNext( headPtr );
    headPtr = newFirst;
  }
   
  // Traverse the list, printing each node
  public void traverse()
  {
    Node p = headPtr;
    while ( p != null )
    {
      System.out.print( p + ", " );
      p = p.getNext();
    }
  }
     
}

QUESTION 7:

Say that traverse() has been called and that the list is empty.

What will traverse() do with an empty list?


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