Problem statement
Given the head of a singly linked list, reverse the list in place and return the new head.
Each node holds a value and a next pointer. Do not create new nodes — re-point the existing ones.
Examples
- Input
head = 1 → 2 → 3 → 4 → 5
- Output
5 → 4 → 3 → 2 → 1
- Input
head = 1 → 2
- Output
2 → 1
- Input
head = (empty)
- Output
(empty)
Why: Return null / None for an empty list.
Constraints
- 0 ≤ number of nodes ≤ 5000
- −5000 ≤ node value ≤ 5000
How to answer it out loud
What it tests: Fundamental pointer reasoning, correctness, and clear testing.
- 1Clarify
Clarify singly versus doubly linked and mutation constraints.
- 2Implement
Track previous, current, and next explicitly.
- 3Verify
Test empty, one-node, and multi-node lists.
From brute force to the best solution
| Approach | Idea | Time | Space |
|---|---|---|---|
| Copy values | Read the values into an array, then write them back in reverse. | O(n) | O(n) |
| Recursion | Reverse the rest of the list, then hook the current node onto its end. | O(n) | O(n) call stack |
| Iterative pointer flipBest | Walk the list once with prev, curr and next, flipping each pointer. | O(n) | O(1) |
Before you flip curr.next, save it — it is your only link to the rest of the list. When the loop ends, prev is the old tail, which is the new head.
Reference solution
Each version is self-contained and has been run against the examples and test cases on this page.
from typing import Optionalclass ListNode: def __init__(self, val=0, next=None): self.val = val self.next = nextdef reverse_list(head: Optional[ListNode]) -> Optional[ListNode]: prev, curr = None, head while curr: nxt = curr.next # save the rest of the list before re-pointing curr.next = prev prev, curr = curr, nxt return prev # old tail = new head- Time
- O(n)
- Space
- O(1)
- Approach
- Iterative pointer flip
Edge cases to run before you say “done”
| Input | Expected | Why it matters |
|---|---|---|
| (empty) | (empty) | The loop must not dereference null. |
| 7 | 7 | A single node points to null afterwards. |
| 1 → 2 → 3 | 3 → 2 → 1 | The old head’s next must become null — otherwise you create a cycle. |
Answer the main question first, then take these on one at a time:
- Can you do it recursively?
- What is the space complexity?
- What changes for a doubly linked list?
Check your recording or written solution against this list:
- Losing the next pointer
- No edge-case test
- Reciting code without reasoning
This guide combines general interview-practice patterns with the public hiring material below. The practice prompt and coaching are PiriPiri AI editorial content, not official Google questions or answers.
Official sources reviewed 20 September 2026.