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

Answer:

Yes.


Inserting another Node

Now there is a one-node linked list. Say that main() calls insertFirst() again:

    // create an empty linked list
    LinkedList list = new LinkedList();  
    
    // insert first node
    list.insertFirst( 5 );
    
    // insert another node
    list.insertFirst( 14 );
public class LinkedList
{
  private Node headPtr = null;
  . . .
  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

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.

empty linked list

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

empty linked list

QUESTION 4:

Could this process continued with a third node?