#206 - Reverse Linked List
Given the head of a singly linked list, reverse the list and return the new head.
| Input | Output |
|---|---|
head = [1,2,3,4,5] | [5,4,3,2,1] |
head = [1,2] | [2,1] |
head = [] | [] |
Solution Space
ts
/**
* Reverses a singly linked list in-place and returns the new head.
*
* @param head Head of the original list (may be null)
* @returns Head of the reversed list
*/
export function reverseList(head: ListNode | null): ListNode | null {
let prev: ListNode | null = null;
let curr = head;
while (curr) {
const next = curr.next; // save next before overwriting
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Approach: iterative pointer reversal – maintain three pointers (`prev`, `curr`, `next`). On each step, point `curr.next` back to `prev`, then advance all three.
Time: O(n) – single pass through the list.
Space: O(1) – only three pointer variables.
Alternative approaches:
| Approach | Idea | Time | Space |
|---|---|---|---|
| Recursive | Base case: single node or null. Recurse on head.next, then set head.next.next = head and head.next = null. | O(n) | O(n) call stack |
Why the iterative method is preferred: identical time complexity with O(1) space instead of O(n) stack frames, and no risk of stack overflow on very long lists.