Three-pointer reversal
Flipping a node's arrow overwrites the only link to the rest of the list, so the rest of the chain must be saved off before you make the cut — that's the entire reason a third pointer exists. Walk forward one node at a time: stash what comes next, point the current node backward into the already-reversed prefix, then slide forward and repeat, so prev trails the reversed part while curr is the node currently being flipped. Reach for it whenever you must reverse links with O(1) extra space.
Details
Animated on: Reverse the singly linked list 1->2->3->4 in place
Problem:Reverse Linked ListEasy
Linked List
step 1 / 15
Input: 1->2->3->4, every arrow points right. Goal: flip all arrows so 4 becomes the head.
- head=0· arr[0] = 1
1FUNCTION reverse(head):2 prev = nothing (the reversed part is empty)3 curr = head4 WHILE curr is not empty:5 next = the node after curr6 make curr point backward to prev7 prev = curr8 curr = next9 END WHILE10 RETURN prev11END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 15 steps
- Input: 1->2->3->4, every arrow points right. Goal: flip all arrows so 4 becomes the head.
- prev = null (the reversed part is empty so far), curr = head node 1. next will be set inside the loop.
- Save next = 2 first — once we flip 1's arrow, this is our only link to the rest of the list.
- Flip: 1.next = prev (null). Node 1's arrow now points backward — it will be the tail of the reversed list.
- Slide the trio right: prev = 1 (head of the reversed part), curr = saved next = 2.
- curr = 2, still in the loop. Save next = 3 before we cut 2's forward arrow.
- Flip: 2.next = prev, so 2 now points back to 1. Reversed part so far: 2->1.
- Advance: prev = 2 (new head of the reversed part), curr jumps to the saved 3.
- Save next = 4. The saved pointer is the lifeline to the not-yet-reversed tail.
- Flip: 3.next = prev (2). Reversed part grows: 3->2->1. Only node 4 still points the old way.
- Advance: prev = 3, curr = 4 — the last node whose arrow still needs flipping.
- curr = 4. next = curr.next is null — nothing after 4, so this is the final flip.
- Flip: 4.next = prev (3). Every arrow now points backward: 4->3->2->1.
- Advance one last time: prev = 4, curr = next = null. The while condition fails — nothing left to reverse.
- Return prev: node 4 is the new head. List reversed to 4->3->2->1 in one pass, O(n) time, O(1) space.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.