Linked lists
prev starts at ∅, cur at the head. One arrow will flip per iteration.
1 / 26How reverse a list works
Walk the list once, flipping each arrow to point backward. The trap: the moment you flip cur.next, you have lost your way forward — the rest of the list is unreachable. That is why next is saved first, every iteration, before the flip. Save, flip, advance: the three-line ritual.
The invariant to say out loud: at the top of every iteration, everything before cur is already reversed (green, arrows pointing left) and prev is its head; everything from cur onward is still the original list. The two halves are disconnected — the saved next pointer is the only bridge, held in a local variable.
This is the most-asked linked-list question in interviews, and the follow-ups are predictable: do it recursively (the recursive version uses O(n) stack space — say so), reverse only positions m to n (LeetCode 92 — same flip, plus careful stitching at both seams), and reverse in k-groups (hard). Master the three-pointer dance here and all of them are variations.
space play / pause · ←→ step
Complexity
| time | O(n) |
|---|---|
| space | O(1) |
| pattern | three pointers |
| arrows flipped | n, exactly |