Intuition
Walk the list once, and at each node flip its next pointer to point backwards to the node we just processed. The trick is keeping three pointers — the one we're rewiring, the one before, and the one after — so the rest of the list isn't lost mid-flip.
Explanation
The mental picture
We have a list 1 → 2 → 3 → None and want to produce 3 → 2 → 1 → None.
Imagine standing at each node in turn and flipping its arrow. The danger is that once you flip 2's arrow to point at 1, you've lost the way to 3. So before flipping, we save a pointer to whatever was next.
The three pointers
prev— the previously visited node (will becomecurr's newnext). Starts asNone.curr— the node we're currently flipping. Starts ashead.nxt— saved reference tocurr.nextso we can move on after rewiring.
Steps
- Initialise
prev = None,curr = head. - While
curris notNone:nxt = curr.next← remember what's comingcurr.next = prev← flip the arrowprev = curr← stepprevforwardcurr = nxt← stepcurrforward
- Return
prev(it's the new head).
Walk-through
head = 1 → 2 → 3 → None.
| step | prev | curr | nxt | after wiring |
|---|---|---|---|---|
| 0 | None | 1 | 2 | 1 → None, list still has 2 → 3 |
| 1 | 1 | 2 | 3 | 2 → 1 |
| 2 | 2 | 3 | None | 3 → 2 |
| 3 | 3 | None | — | loop ends; return prev = 3 |
Result: 3 → 2 → 1 → None. ✓
Why we need nxt
After we set curr.next = prev, curr.next no longer points at the next node — it points back to prev. If we then write curr = curr.next, we'd walk backwards. Saving nxt ahead of time keeps the forward path alive.
Edge cases
- Empty list (
head is None): thewhilebody never runs; returnprev = None. - Single node: one iteration sets
curr.next = None(it was alreadyNone), thenprev = node,curr = None; returnnode.
Complexity
- Time:
O(n)— each node is visited exactly once. - Space:
O(1)— three pointer variables.
Implementation
import java.util.*;
class Solution {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nxt = curr.next;
curr.next = prev;
prev = curr;
curr = nxt;
}
return prev;
}
}