Yes.
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:
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.
Finally ( // 3 ) a reference to the new node is copied into
headPtr, and the two-node list is complete:
The list has a new first node. Sometimes the first node is called head of the list or sometimes the front of the list.
Could this process continue with a third node?