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

Answer:

Notice that you don't need an if statement because the value that == computes is the value to return.

Here is the class so far:

// LinkedList.java
//
public class LinkedList
{
   private Node headPtr = null;
  
  // The constructor creates an empty list
  public LinkedList()
  {
    headPtr = null;
  }

  // Determine if the List is empty
  public boolean isEmpty()
  {
     return headPtr == null;
  }
  
  // Insert one Node containing data at the head
  // of the list.
  public void insertFirst( int data )
  {
    Node newFirst = new Node( data );
    newFirst.setNext( headPtr );
    headPtr = newFirst;
  }
}

Insert First

main() now inserts the first Node

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

The first time it is called, a one-node chain is created.


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:

linked list and one un-linked node

Then at ( // 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 at ( // 3 ) the reference to the new node is copied into headPtr :

linked list with one node

QUESTION 4:

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


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