next up previous index
Next: Testing for the presence Up: Linked Lists Previous: Insertion   Index


Deletion

The firstItem method only returns the first data item, it doesn't remove it. If you wish to remove the first item, you need the following method:

public void removeFirst() {
    if (head != null) {
        head = head.next;
        --size;
    } else {
        throw new NoSuchElementException();
    }
}
Provided the list is not empty, this removes the first item. The new list is now headed by the next field of the old list. The new list is shorter by 1. Note that the node that was previously at the head of the list is no longer accessible, in virtue of the reassignment head = head.next. In Java, you rely on the garbage collector to return this unused storage to the operating system.



Peter Williams 2005-06-07