Close

Reversing a doubly linked list

Given a doubly linked list, how do we reverse it by just re-arranging the pointers?
Here is an example of input/output.
The following picture depicts how we re-arrange the pointers.

Here is the Java implementation.

/**
* Created with IntelliJ IDEA.
* User: Ravi
* Date: 11/6/13
* Time: 5:45 AM
* To change this template use File | Settings | File Templates.
*/
public class DoublyLinkedListTest {
public static void main(String[] args)
{
Node head = null;
head = Insert(head, 1);
head = Insert(head, 2);
head = Insert(head, 3);
head = Insert(head, 4);
head = Insert(head, 5);
Print(head);
head = Reverse(head);
Print(head);
}
static class Node
{
public int data;
public Node prev;
public Node next;
}
public static Node Reverse(Node head)
{
//If 0 or 1 node? no need to reverse; trivial case
if( head == null || head.next == null )
return head;
Node prevNode = null;
Node curNode = head;
while ( curNode != null )
{
prevNode = curNode.prev;
curNode.prev = curNode.next;
curNode.next = prevNode;
curNode = curNode.prev;
}
return prevNode.prev;
}
public static void Print(Node head)
{
for( Node ptr = head; ptr != null ; ptr = ptr.next )
{
System.out.print(ptr.data + " ");
}
System.out.println();
}
public static Node Insert(Node head, int data)
{
if( head == null )
{
head = new Node();
head.data = data;
head.next = null;
head.prev = null;
return head;
}
Node newNode = new Node();
newNode.data = data;
newNode.next = head;
head.prev = newNode;
newNode.prev = null;
return newNode;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *