Wednesday, September 7, 2011

How to reverse a doubly linked list ?

I talked about how to reverse a singly linked list earlier. That was slightly tricky to understand.

Reversing a doubly linked list is relatively easy. The logic is : You need to keep on changing the next and previous pointers as you traverse the entire list. Here is the code snippet in Java :

public void reverse()
{
    if (first == null) 
          return;

    DoubleNode previous = first;
    DoubleNode current = first.next;
    first.next = null;
    while (current != null)
    {
            DoubleNode next = current.next;
            current.next = previous;
            previous = current;
            current = next;
    }
    first = previous;
}


0 comments:

Post a Comment