Reverse a Doubly Linked List
Problem Statement:β
Given aΒ doubly linked list. Your task is toΒ reverseΒ the doubly linked list and return its head.
Examples:
Input:LinkedList: 3 <-> 4 <-> 5
Output:5 <-> 4 <-> 3

Input:LinkedList: 75 <-> 122 <-> 59 <-> 196
Output:196 <-> 59 <-> 122 <-> 75

Expected Time Complexity:Β O(n).
-
Example:
β Solution: In-Place Reversal of Doubly Linked Listβ
/*
class DLLNode {
public:
int data;
DLLNode *next;
DLLNode *prev;
DLLNode(int val) {
data = val;
this->next = NULL;
this->prev = NULL;
}
};
*/
class Solution {
public:
// Function to reverse a doubly linked list
DLLNode* reverseDLL(DLLNode* head) {
if(head == NULL || head->next == NULL) return head;
DLLNode* curr = head;
DLLNode* prevNode = NULL;
while(curr != NULL){
prevNode = curr->prev; // Store previous
curr->prev = curr->next; // Swap next and prev
curr->next = prevNode; // Move forward
curr = curr->prev; // Continue in swapped direction
}
// Return new head (prev of last non-null curr)
return prevNode->prev;
}
};
π How It Worksβ
- Start from the head of the DLL.
- At each node, swap its
nextandprevpointers. - After the loop ends,
currbecomesNULL, andprevNodewill point to the last node processed. - The new head is at
prevNode->prev.
π§© Key Swap Logicβ
curr->prev = curr->next;
curr->next = prevNode;
This inverts the direction of the list.
β±οΈ Time & Space Complexityβ
| Operation | Time | Space |
|---|---|---|
| Reversal | O(N) | O(1) |
β οΈ Edge Casesβ
- Empty list β returns
NULL - Single node β returns the node as-is
- List with even/odd number of nodes
π‘ Other Approachesβ
- Using stack: Push nodes into stack and re-link from top β uses O(N) space.
- Recursive reversal: Elegant, but not space-efficient due to recursion stack.
π Related Problemsβ
- Reverse a singly linked list
- Flatten a multilevel doubly linked list
- Rotate DLL by k nodes
- Check if DLL is palindrome
π Level Up Your Engineering Mindset
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Official Hub
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.