(1) Search for the next-to-last node, (2) unlink the last node from it.
Delete last is tricky because you need a reference to the next-to-last node in order to unlink the last node. But there are special cases where there is no next-to-last node: an empty list and a list with just one node. The method tests for these cases.
public void deleteLast() { // if list is empty do nothing if ( headPtr == null ) { return; } // if list has one node, unlink it // to create an empty list if ( headPtr.getNext() == null ) { headPtr = null; return; } // search for the next to last node Node p = headPtr; while ( p.getNext().getNext() != null ) p = p.getNext(); // unlink the last node p.setNext( null ); }
How could you delete the entire LinkedList
?