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

Answer:

Yes.


Inserting another Node

Now there is a one-node linked list. Another call of insertFirst() links in a new node:

    // create an empty linked list
    LinkedList list = new LinkedList();  
    
    // insert first node
    list.insertFirst( 5 );
    
    // insert another node
    list.insertFirst( 14 );

After insertFirst( 5 ) headPtr points to a node (see picture.)

Then list.insertFirst( 14 ) inserts a new Node as the first node, and what was the first Node becomes the second in the list.

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

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

linked list with one node

At ( // 2 ) the value in headPtr is copied into the new Node. This copies a pointer to the current first node from headPtr into the next member of the new Node.

linked list with one node

Finally ( // 3 ) a reference to the new node is copied into headPtr, and the two-node list is complete:

linked list with two nodes

The list has a new first node. Sometimes the first node is called head of the list or sometimes the front of the list.


QUESTION 5:

Could this process continue with a third node?


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