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


Reversing a list

It is a simple matter to reverse a list, at least so far as the code is concerned. It takes a little more thought to understand why it works.

public void reverse() {
    ListNode current = head;
    head = null;
    while (current != null) {
        ListNode save = current;
        current = current.next;
        save.next = head;
        head = save;
    }
}
The idea is to build up a new list from the old one, by walking down the old list, stripping off each node in turn and attaching it to the front of the new list. You need to work through the code yourself to be satisfied that it works. Note that no new storage is required. All that happens is that references to existing nodes are reassigned.



Peter Williams 2005-06-07