Learning Outcome
After this lesson, you should be able to reverse a linked list in-place while carefully preserving the next node before changing pointers.
Problem Statement
Given the head of a singly linked list, reverse the list and return the new head.
| Input | Output | Why |
|---|---|---|
1 -> 2 -> 3 -> 4 | 4 -> 3 -> 2 -> 1 | Every pointer direction is reversed. |
Brute Force Approach
Copy all node values into an array, then rebuild a new linked list in reverse order.
This is easy to visualize, but it uses O(n) extra space and does not practice pointer manipulation.
Optimized Approach
Use three pointers: prev, curr, and nextNode. Save curr.next, point curr.next to prev, then move both pointers forward.
The key safety rule is to save the next node before changing curr.next.
Exact Pseudocode
prev = null
curr = head
while curr is not null:
nextNode = curr.next
curr.next = prev
prev = curr
curr = nextNode
return prev
Reference Code
class Solution:
def reverseList(self, head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prevSample Dry Run
| Step | curr | nextNode | prev after reversal |
|---|---|---|---|
| Start | 1 | - | null |
| Reverse 1 | 1 | 2 | 1 -> null |
| Reverse 2 | 2 | 3 | 2 -> 1 -> null |
| Reverse 3 | 3 | 4 | 3 -> 2 -> 1 -> null |
| Finish | null | - | Return 4 -> 3 -> 2 -> 1 |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n) | Each node is visited once. |
| Space | O(1) | The reversal is in-place. |
Edge Cases
- Empty list returns
null. - Single-node list returns the same node.
- Saving
nextNodeis required before changingcurr.next.
Interview Checklist
- Save the next node before rewiring.
- Move
prevandcurrin the right order. - Return
prev, not the old head.
FAQs
Why do we need three pointers?
prev builds the reversed part, curr is the node being processed, and nextNode preserves the remaining list.
Can this be done recursively?
Yes, but the iterative version is usually easier to explain and uses O(1) extra space.
What is the core pattern?
Pointer reversal.