842. Reverse a singly linked list in place
A log buffer is kept as a singly linked list from oldest to newest, and you need it newest first without allocating new nodes.
A node class is provided: ListNode(val, next=None). Write reverse_list(head) that reverses the list in place and returns the new head. The input can be None.
def reverse_list(head)Example 1
1 -> 2 -> 3 becomes 3 -> 2 -> 1.
Example 2
Input: to_list(reverse_list(build([9])))
Output: [9]
Example 3
Input: to_list(reverse_list(build([4, 5])))
Output: [5, 4]
Constraints
- 0 <= list length <= 100,000
Hint 1
prev starts as None.
Hint 2
Save current.next before overwriting it.
Hint 3
Return prev at the end.
Common mistakes
- Overwriting next before saving it, which cuts off the rest of the list.
- Returning the old head.
- Using recursion on a very long list.
Understand the idea
In-place list reversal is a three-pointer walk: previous, current and next. Each step flips one arrow. For 1 -> 2 -> 3: flip 1 to point at None, then 2 to point at 1, then 3 to point at 2, and return 3. A recursive version is shorter but uses O(n) stack, which can overflow on long lists.