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

Answer:

Replace

Node node0 = new Node( 223 ); 

with

Node node0 = null 

Another Traversal

It seems a little silly to write a program that creates a list with no Nodes. But in realistic real-world programs data structures repeatedly grow and shrink and sometimes become empty.

Let us practice thinking about linked lists: Here is a program that builds a linked list, and then counts the nodes in it. Pretend that the linked list was created dynamically from external data so it is not obvious how many nodes it has.


public class NodeCounter
{
  public static void main ( String[] args )
  {
    Node node0 = new Node( 4 );  
    
    Node node1 = new Node( 2 );
    node0.setNext( node1 );
    
    Node node2 = new Node( 9 );  
    node1.setNext( node2 );
    
    Node node3 = new Node( 5 );  
    node2.setNext( node3 );
    
    Node node4 = new Node( 7 );  
    node3.setNext( node4 );
    
    Node node5 = new Node( 13 );  
    node4.setNext( node5 );
       
    // Traverse the Linked List in a loop
    Node p = node0;
    int count = 0;
    while (  p != null  )
    {
      _______________ ;
      
      p = p.getNext();
    }
    System.out.println( "Count of nodes: " + count );
  }
}

QUESTION 12:

What should go in the blank to count the number of nodes?


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