Full answer
Problem
Given the head of a singly linked list, reverse it and return the new head.
Example: 1 -> 2 -> 3 -> 4 -> 5 becomes 5 -> 4 -> 3 -> 2 -> 1.
Constraints: 0 <= n <= 5000 nodes.
Brute force
Copy the values into a Python list, reverse it, and build a new list (or write the values back). O(n) time but O(n) extra space, and it does not show pointer handling, which is what the question tests.
Optimal approach
Iterative:
prev = None.- While
head:nxt = head.next;head.next = prev;prev = head;head = nxt. - Return
prev.
Recursive:
- Base case: empty list or single node, return it.
- Reverse the rest:
new_head = reverse(head.next). head.next.next = head;head.next = None; returnnew_head.
Why it works
Invariant for the iterative loop: prev is the head of the already reversed prefix, and head is the head of the untouched remainder. Each step moves one node from the remainder to the front of the reversed part. Saving nxt first is essential; otherwise the rest of the list is lost when head.next is overwritten.
In the recursive version, after the call, head.next is the tail of the reversed rest, so setting its next to head appends head at the end.
Complexity
O(n) time for both. Iterative O(1) extra space; recursive O(n) stack, which hits Python's default recursion limit (about 1000) on long lists.
Code
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def from_list(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def reverse_list(head):
"""Reverse a singly linked list iteratively. O(n) time, O(1) extra space."""
prev = None
while head:
nxt = head.next # save the rest of the list
head.next = prev # point this node backwards
prev = head
head = nxt
return prev
def reverse_list_recursive(head):
"""O(n) time, O(n) call stack."""
if head is None or head.next is None:
return head
new_head = reverse_list_recursive(head.next)
head.next.next = head
head.next = None
return new_head
if __name__ == "__main__":
for f in (reverse_list, reverse_list_recursive):
assert to_list(f(from_list([1, 2, 3, 4, 5]))) == [5, 4, 3, 2, 1]
assert to_list(f(from_list([1, 2]))) == [2, 1]
assert to_list(f(from_list([7]))) == [7]
assert f(None) is None
print("all tests passed")Save as a39_reverse_linked_list.py and run python3 a39_reverse_linked_list.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list returns None. A single node returns itself. Two nodes test the pointer swap. Forgetting head.next = None in the recursive version creates a cycle between the first two nodes.
Pattern
Pointer rewiring with a saved next pointer. Building blocks for reversing a sublist between positions m and n, reversing in groups of k, checking a palindrome list, and adding numbers stored as lists.
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def from_list(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def reverse_list(head):
"""Reverse a singly linked list iteratively. O(n) time, O(1) extra space."""
prev = None
while head:
nxt = head.next # save the rest of the list
head.next = prev # point this node backwards
prev = head
head = nxt
return prev
def reverse_list_recursive(head):
"""O(n) time, O(n) call stack."""
if head is None or head.next is None:
return head
new_head = reverse_list_recursive(head.next)
head.next.next = head
head.next = None
return new_head
if __name__ == "__main__":
for f in (reverse_list, reverse_list_recursive):
assert to_list(f(from_list([1, 2, 3, 4, 5]))) == [5, 4, 3, 2, 1]
assert to_list(f(from_list([1, 2]))) == [2, 1]
assert to_list(f(from_list([7]))) == [7]
assert f(None) is None
print("all tests passed")Iterative and recursive reversal with list helpers; both pass the same tests, including the empty list.
Complexity
Time: O(n). Space: O(1) iterative; O(n) recursive call stack. The recursive version is limited by Python's recursion depth on long lists.
By level
Fresher: Writes the iterative three-pointer reversal and traces it on a short list. Should test the empty list and a single node.
Mid: Gives both versions, states the invariant and explains the recursion depth limit in Python. Explains why next must be saved before rewiring.
Senior: Extends to sublist and k-group reversal, discusses immutable list designs and memory safety when rewiring pointers. Explains the risk of deep recursion in Python.
Key points
- Save next before rewiring
- prev is the head of the reversed part
- Return prev at the end
- Iterative uses O(1) space
- Recursive uses O(n) stack
Common mistakes
- Losing the rest of the list by overwriting next first
- Returning the old head
- Creating a cycle by not clearing head.next in recursion
- Copying values into a list when in-place is asked
Follow-ups
- How would you reverse only positions m to n?
- How do you reverse in groups of k?
- How would you check whether a linked list is a palindrome?
Tips
- Draw three boxes for prev, current and next
- State the loop invariant
- Test empty, one and two nodes
Evaluation rubric
- Correct in-place reversal
- Correct return value
- Handles empty and single-node lists
- Correct space analysis