Yes. In this case the headPtr
is null
.
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 ); } }
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
:
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.
Finally ( // 3 ) a reference to the new node is copied into headPtr
:
After all this, do we have a legitimate one-node linked list?