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

Answer:

All you need to do is change headPtr so that it points to the second node (if any) or contains null (if no second node or the list was empty to start with).


Delete First

Here is a the deleteFirst() method that may be added to LinkedList:

  public void deleteFirst()
  {
    if ( headPtr != null ) 
    {    
      headPtr = headPtr.getNext();  // headPtr now points at second node, or
                                    // is null if there was no second node.
    }
  }

Does the method work? It looks easy enough, but check that it works for all situations. Sometimes programmers overlook a situation.

Case I. List is already empty.

In this case, headPtr is null. The condition of the if statement detects this and the method does nothing.

Case II. One-node list.

headPtr currently points to that single node. That node's next member is null. So headPtr = headPtr.getNext() copies a null into headPtr, making the list empty.

Case III. Many-node list.

headPtr points to the first node. That node's next member is points to the second node. So headPtr = headPtr.getNext() copies a pointer to the second node into headPtr, removing the previous first node from the list.

QUESTION 11:

What becomes of the node that has been unlinked from the list?


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