← Linked List
Problem
You're given the head of a singly linked list. Reverse it in place and return the new head — the last node becomes first, the first becomes last.
Signal
"Reverse this list in place" means re-pointing every next link one at a time
— you need a running trio of pointers (previous, current, next) since once you
overwrite current.next you lose the way forward unless you saved it first.
Approach
Walk the list once. At each node, save its next before you overwrite it,
point current.next back at prev, then slide prev and current forward
one step. When current runs out, prev is sitting on the new head.
Skeleton
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
Solution
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head: ListNode | None) -> ListNode | None:
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
Complexity
O(n) time — one pass over every node. O(1) space — three pointers, no recursion stack.
Pitfalls
- Forgetting to save
curr.nextbefore reassigning it — you'd sever the list and strand everything after the current node. - A recursive version is equally correct but costs O(n) call-stack space; know both, but the iterative version is the safer default to write under pressure.
- Returning
headinstead ofprevat the end —headis now the tail of the reversed list, not the new head.