Data Structures · Visualization
Doubly LL: Reverse
Doubly Linked List
Reversing a doubly linked list swaps the role of 'next' and 'prev' at every node, then swaps head and tail. Time: O(n). Space: O(1).
Big-O: Insert/delete at either end O(1); extra memory for prev pointers.
Doubly LL: Reverse
Doubly Linked ListReversing a doubly linked list swaps the role of 'next' and 'prev' at every node, then swaps head and tail. Because every node already has both pointers, no extra pointer-chasing is needed — you just walk the list once, flipping each node's two links.
How Reverse Works
- Start current at head.
- For each node, swap its next and prev pointers.
- Move to what is now current.prev (the old current.next) to continue forward through the original list.
- When done, swap head and tail.
Reverse Worked Example
Input: null <- 1 <-> 2 <-> 3 -> null
- At node 1: swap next/prev → next=null, prev=2
- At node 2: swap next/prev → next=1, prev=3
- At node 3: swap next/prev → next=2, prev=null
- Swap head and tail: head=3, tail=1
Output: null <- 3 <-> 2 <-> 1 -> null
Press ▶ Run to watch it step by step.
def reverse(head):
cur = head
prev = None
while cur:
nxt = cur.next
cur.next = prev # swap prev/next
cur.prev = nxt
prev = cur
cur = nxt
return prev # new head
# example: reverse on [1, 2, 3]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Reverse Time & Space Complexity
When to Use Reverse
- Reversing playback order in a media player
- Flipping the direction of an undo/redo history
- A common interview variation on the singly linked list reversal problem
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.