next up previous index
Next: Deletion Up: Linked Lists Previous: Instance variables and the   Index


Insertion

Having created an empty list, we need to be able to insert into it. The following method inserts an item at the head of the list, whether the list was previously empty or not:

public void addFirst(Object item) {
    head = new ListNode(item, head);
    ++size;
}
In the first line, a new list node is created, which is to be the head of the new list. Its data field is set to the new item and its next field is set to the head of the old list. The size of the list increases by one.

It is convenient to be able to view the first item in the list:

public Object firstItem() {
    if (head != null) {
        return head.data;
    } else {
        throw new NoSuchElementException();
    }
}
An exception must be raised if the list is empty.



Peter Williams 2005-06-07