Keeping head reference while traversing Linked Lists?

I'm revising Linked Lists and in the book I'm using they suggest the following code to search for a specific value:

public ListElement<Integer> find( ListElement<Integer> head, int data ){
   ListElement<Integer> elem = head;
   while( elem != null && elem.value() != data ){
       elem = elem.next();
   }
   return elem;
}

But, cannot we iterate on head directly?

Jon Skeet
people
quotationmark

You can - but then it would be a somewhat misleading piece of code. If I look at a variable called head, I'd expect it to be the head of a list - whereas if I do:

head = head.next();

... then head refers to something which isn't the head of the list. It's always worrying when a variable name implies something that isn't true. It would technically work, but it would be a bad idea.

I would personally write the code more like this:

public ListElement<Integer> find(ListElement<Integer> head, int data) {
    for (ListElement<Integer> current = head;
           current != null;
           current = current.next()) {
        if (current.value == data) {
            return current;
        }
    }
    // No entry found
    return null;
}

That way the "not found" case is more naturally distinct from the "found" case - it would be easier to change it to throw an exception if the value isn't found, for example.

people

See more on this question at Stackoverflow