Linked lists

Reverse a list · source
1function reverse(head: Node | null) {
2 let prev: Node | null = null;
3 let cur = head;
4 while (cur !== null) {
5 const next = cur.next;
6 cur.next = prev;
7 prev = cur;
8 cur = next;
9 }
10 return prev;
11}
Reverse a list · liveThree pointers walk the list, flipping one arrow per step.

prev starts at ∅, cur at the head. One arrow will flip per iteration.

1 / 26

How 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

timeO(n)
spaceO(1)
patternthree pointers
arrows flippedn, exactly