00:00

Reverse a Doubly Linked List

In this tutorial we are going to talk about how to reverse a doubly linked list using the Java program.

In order to reverse a doubly linked list, we need to iterate through the list while swapping the next and previous pointers of each node. Once we reach the end of the list, the head pointer will point to the last node of the list.

Let's understand the reverse of a doubly linked list with the given example below:

Reverse a Doubly Linked List

Example: Reverse a Doubly Linked List in Java

Class: Node

Node.java
public class Node {
  int data;   // Data stored in the node
  Node prev;  // Reference to the next node in the list
  Node next;  // Reference to the previous node in the list

  // Constructor to initialize a new node with data
  Node(int new_data) {
    data = new_data;
    prev = null;
    next = null;
  }
}

Class: ReverseDoublyLinkedList

ReverseDoublyLinkedList.java
// Java program to reverse a doubly linked list using recursion approach
public class ReverseDoublyLinkedList {
  static Node head;

  // Method to insert a node in doubly linked list
  static void insertNode(int data) {
    Node newNode = new Node(data);
    Node last = head;
    if (head == null) {
      head = newNode;
      return;
    }
    while (last.next != null) {
      last = last.next;
    }
    last.next = newNode;
    newNode.prev = last;
  }

  // Method to reverse a doubly linked list using recursive approach
  static Node reverseList(Node node) {

    // If node is null that means list is empty
    if (node == null)
      return null;

    // Swap the next and previous pointers
    Node temp = node.prev;
    node.prev = node.next;
    node.next = temp;

    // If prev is null after swap, this is the new head
    if (node.prev == null) {
      return node;
    }

    // Recurse for the next node
    return reverseList(node.prev);
  }

  // Method to print a list
  static void printList(Node node) {
    while (node != null) {
      System.out.print(node.data + " ");
      node = node.next;
    }
    System.out.println();
  }

  public static void main(String[] args) {
    // Insert node into a doubly linked list
    insertNode(10);
    insertNode(20);
    insertNode(30);
    insertNode(40);
    insertNode(50);

    System.out.println("Original doubly linked list:");
    printList(head);

    // Reverse the doubly linked list
    head = reverseList(head);

    System.out.println("Reversed doubly linked list:");
    printList(head);
  }
}
Output
Original doubly linked list:
10 20 30 40 50
Reversed doubly linked list:
50 40 30 20 10

Time Complexity: O(n)

Auxiliary Space: O(n)

here n means the total number of nodes in a doubly linked list.