You are given a doubly-linked list of size 'N', consisting of positive integers. Now your task is to reverse it and return the head of the modified list.
A doubly linked list is a kind of linked list that is bidirectional, meaning it can be traversed in both forward and backward directions.
Example:
Input:
4
4 3 2 1
This means you have been given doubly linked list of size 4 = 4 <-> 3 <-> 2 <-> 1.
Output:
1 2 3 4
This means after reversing the doubly linked list it becomes 1 <-> 2 <-> 3 <-> 4.
The first line contains an integer 'N', the size of the linked list.
The second line contains 'N' space-separated integers.
Output format :
The output contains all the integers of the reversed doubly linked list.
Note :
You don’t need to print anything. Just implement the given function.
8
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
Input: 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6 <-> 7 <-> 8
Output: 8 <-> 7 <-> 6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1
Explanation: It's self explanatory.
5
5 8 4 9 1
1 9 4 8 5
1 <= 'N' <= 10^3
0 <= 'data' <= 10^3
Where 'N' is the size of the doubly linked list.
Time Limit: 1 sec
We need to swap next and prev pointers between every two consecutive nodes.
The idea is to use recursion and the given function will iterate the doubly linked list in the previous direction by calling itself recursively to reverse it.
Base condition = If the node is NULL then return NULL.
Recursive calls = Swap the next and prev pointers.
O(N), where N is the length of the doubly linked list.
We are traversing a linked list of size N that takes O(N) time. Hence, the overall Time Complexity is O(N).
O(N), where N is the length of the doubly linked list.
We are making N recursive calls that take O(N) Space Complexity. Hence, the overall Space Complexity is O(N).