How can you reverse a double linked list?
💡Strategies for Solving This Problem
The Swap Pattern
Got this at Meta. It's simpler than reversing a singly linked list in some ways - you have both prev and next pointers to work with.
The Problem
Reverse the direction of all pointers in a doubly linked list. What was next becomes prev, what was prev becomes next.
Example:
Original: 1 <-> 2 <-> 3 <-> 4 Reversed: 4 <-> 3 <-> 2 <-> 1
Key Insight
For each node, swap its prev and next pointers. That's it. No need to track previous node like in singly linked list.
The Algorithm
- Start at head
- For each node: swap node.prev and node.next
- Move to next node (which is now in node.prev!)
- Return what was the last node (now the new head)
O(n) time, O(1) space. Single pass through the list.
The Tricky Part
After swapping pointers, "next" is now in the prev field. You need to move to node.prev to go forward. This confuses people.
Alternative: Three Pointer Approach
Keep track of prev, current, and next. Similar to singly linked list reversal but swap both directions. More verbose but maybe clearer.
At Meta
My interviewer asked "How is this different from reversing a singly linked list?" The key difference: you don't need to track the previous node separately because each node already has a prev pointer.
Then asked about edge cases: empty list, single node, two nodes. All work with the same code.