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;
}

5 comments:

Konrad said...

THX, was helpfull!!!

skarthz said...

Hi,

This is the same as the reversal of the singly linked list.

I couldn't see the "previous" pointer/reference getting changed anywhere.

Biyya said...

This method doesn't reverse. It only duplicates them.

Anonymous said...

pwnage zükerün

Rajitha said...

The previous pointer should also be updated as below

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