next up previous index
Next: Reversing a list Up: Linked Lists Previous: Deletion   Index

Testing for the presence of an item

Here is a simple procedure which tests whether or not a list contains a given item.
public boolean contains(Object item) {
    ListNode current = head;
    while (current != null) {
        if (item.equals(current.data)) {
            return true;
        } else {
            current = current.next;
        }
    }
    return false;
}
This takes an item and returns true or false depending on whether or not the item is present. The idea is to walk down the list comparing the current item to the item of interest. For this purpose we introduce a local list node variable current. This is initialised to the head of the list. The while loop walks down the list, using the reassignment current = current.next, until it either finds the item, in which case it returns true, or else until it reaches the end of the list with current == null. In the latter case, control reaches the last line of code and false is returned. Note that the method tests for equality by invoking the equals method of the current item. This might be different for different items.



Peter Williams 2005-06-07