Reverse Linked List
Reverse a singly linked list in place. Walk the list with three pointers: save next, point curr.next back at prev, then step both forward. When curr falls off the end, prev is the new head.
Traced input: head = [1, 2, 3, 4, 5] → [5, 4, 3, 2, 1]. Original problem: neetcode.io/problems/reverse-a-linked-list
Complexity
BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)
Each node's pointer is flipped once.
Key idea
- Everything before
curris already reversed and starts atprev. - Save
curr.nextbefore overwriting it, or the rest of the list is lost. - The loop ends with
curr == null; returnprev. - The recursive version is elegant but uses O(n) stack.
Common mistakes
- Overwriting
curr.nextbefore saving it. - Returning
head(now the tail) instead ofprev. - Forgetting that the old head's
nextmust become null.
Solution
Java
ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}Python
def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prevC++
ListNode* reverseList(ListNode* head) {
ListNode *prev = nullptr, *curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}Edge cases
Each one has its own trace in the interactive view.
| Case | Input | Answer |
|---|---|---|
| Empty list The loop never runs; return null. | head = [] | [] |
| Single node One flip to null. | head = [7] | [7] |
| Two nodes The smallest case where links actually change direction. | head = [1, 2] | [2, 1] |