Linked list box = value · slot = next pointer · ∅ = null
public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nxt = curr.next; // save the rest curr.next = prev; // flip the arrow prev = curr; curr = nxt; } return prev;}
- prev
- —
- curr
- —
- nxt
- —
- reversed
- —
- rest
- —
Why it works
- Brute force copies: push every value on a stack (or into an array) and rebuild the list. O(n) time but O(n) extra space. Rewiring the existing arrows needs O(1).
- The invariant:
prevheads the already-reversed part andcurrheads the untouched rest. Each pass moves one node from the rest to the front of the reversed part. - Order matters.
curr.next = prevdestroys the only link to the rest, sonxtmust be saved first. Swap lines 5 and 6 and the list is cut off after one node. - Return
prev, notcurr: the loop ends whencurris null, andprevthen holds the old tail, the new head. Empty and one-node lists need no special case. - One pass, three pointers: O(n) time, O(1) space.
- Recursive version:
ListNode newHead = reverseList(head.next); head.next.next = head; head.next = null; return newHead;(base case:head == null || head.next == nullreturnshead). Same O(n) time, but O(n) call stack: a very long list can throwStackOverflowError. Reversing only part of a list (LeetCode 92) reuses the same three-pointer loop.