Reverse a Doubly Linked List

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


 

1. Iterative solution

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

 

Download   Run Code

Output:

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

 

2. Recursive solution

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

 

Download   Run Code

Output:

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

 
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of