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

Answer:

Yes. In this case the headPtr is null.


Insert First

A linked list without any nodes is called empty. However, the LinkedList object still exists. Here is a tester method for the LinkedList class that creates an empty list:

public class LinkedListTester
{
  public static void main( String[] args )
  {
    // create an empty linked list
    LinkedList list = new LinkedList();  
    
    // insert first node
    list.insertFirst( 5 );
  }
}
empty linked list

After an empty list has been created, nodes can be linked into a chain using list.insertFirst() . The first time it is called, the first node of the chain is created. Here is what list.insertFirst( 5 ) does:

  public void insertFirst( int data )
  {
    Node newFirst = new Node( data );  // 1
    newFirst.setNext( headPtr );       // 2
    headPtr = newFirst;                // 3
  }

The statement at ( // 1 ) creates a new Node:

empty linked list

Then ( // 2 ) the value in headPtr is copied into the new Node. This copies a null from headPtr into the next member of the new Node (which already has a null). This does not change the picture, but later on this step is important.

empty linked list

Finally ( // 3 ) a reference to the new node is copied into headPtr :

empty linked list

QUESTION 3:

After all this, do we have a legitimate one-node linked list?