Reverse Linked List
easyTests passed 2026-11-11v1.0.01. Core Invariant / The Trick
Maintain `prev = None` and `curr = head`. Before reversing `curr.next = prev`, save `nxt = curr.next`, then advance `prev, curr = curr, nxt`. Return `prev`.
2. Complexity Bounds & Proof
Visits each node once redirecting one pointer with constant auxiliary variables.
3. Minimal Idiomatic Code
def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev4. Failure Modes & Interview Follow-ups
Pitfalls:- Dropping `nxt` before mutating `curr.next` loses the rest of the list.
- Returning `head` instead of `prev` yields only the old head node with `next = null`.
Follow-ups:- Recursive version uses O(N) call stack space; Reverse Linked List II reverses a slice `[left, right]` with a dummy node.
Personal Notes & Scratchpad (Local-First Yjs CRDT)
Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.
Related Invariants
Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.