Given the head of a Doubly Linked List, reverse the list in-place so that the first node becomes the last, the second node becomes the second last, and so on. Return the new head of the reversed list.
[Naive Approach] Using Recursion - O(n) Time and O(n) Space
The idea is to reverse the doubly linked list by swapping the next and prev pointers of each node. Once the pointers of the current node are swapped, we make a recursive call on the new prev pointer (which originally was the next node) to process the rest of the list.
Output
3 <-> 2 <-> 1
[Expected Approach] Using Two Pointers - O(n) Time and O(1) Space
The idea is to reverse doubly linked list using two pointers for traversing through the list and swapping the next and previous pointers of every two consecutive nodes.
Step-by-step algorithm:
Initialize prevNode as NULL and set currNode to the head of the list.
Traverse the linked list until currNode becomes NULL.
For each node, swap currNode->next and currNode->prev.
Move currNode to the next node using currNode = currNode->prev.
After traversal, prevNode points to the second node of the reversed list.