In this post, we will see how to reverse a doubly linked list using iteration and recursion.

Practice this problem

1. Iterative Solution

The idea is simple – Traverse the list and swap next and prev pointers for each node. Finally, update head pointer to point to the last node.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

Original list: 5 —> 4 —> 3 —> 2 —> 1 —> NULL
Reversed list: 1 —> 2 —> 3 —> 4 —> 5 —> NULL

Java


Download  Run Code

Output:

Original list: 5 —> 4 —> 3 —> 2 —> 1 —> null
Reversed list: 1 —> 2 —> 3 —> 4 —> 5 —> null

Python


Download  Run Code

Output:

Original list: 5 —> 4 —> 3 —> 2 —> 1 —> None
Reversed list: 1 —> 2 —> 3 —> 4 —> 5 —> None

2. Recursive Solution

We can also solve this problem recursively by passing current node information in the recursion itself. This is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

Original list: 5 —> 4 —> 3 —> 2 —> 1 —> NULL
Reversed list: 1 —> 2 —> 3 —> 4 —> 5 —> NULL

Java


Download  Run Code

Output:

Original list: 5 —> 4 —> 3 —> 2 —> 1 —> null
Reversed list: 1 —> 2 —> 3 —> 4 —> 5 —> null

Python


Download  Run Code

Output:

Original list: 5 —> 4 —> 3 —> 2 —> 1 —> None
Reversed list: 1 —> 2 —> 3 —> 4 —> 5 —> None

The time complexity of both above-discussed methods is O(n), where n is the length of the linked list. The iterative version doesn’t require any extra space, whereas the recursive version use stack space proportional to the lists’ length.