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).
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 theif
statement detects this and the method does nothing.
Case II. One-node list.
headPtr
currently points to that single node. That node'snext
member isnull
. SoheadPtr = headPtr.getNext()
copies anull
intoheadPtr
, making the list empty.
Case III. Many-node list.
headPtr
points to the first node. That node'snext
member is points to the second node. SoheadPtr = headPtr.getNext()
copies a pointer to the second node intoheadPtr
, removing the previous first node from the list.
What becomes of the node that has been unlinked from the list?