The problem, in one line. Given the first node of a singly linked list, turn every arrow around and return the new first node. LeetCode 206.
The tell. The list can only be walked forward, and the answer is the same chain read backwards. When the job is to change which node points where, you are rewiring, and the danger is cutting the only road to the rest.
The wrong first idea
Walk the list once, push every value into an array, then build a fresh list from the array read backwards.
vals = []
while head: vals.append(head.val); head = head.next
It is correct and linear. It also makes n new nodes and rewires nothing, and the usual follow-up asks for constant extra memory. The point of the problem is to turn the arrows of the nodes you already have.
The invariant
Clinic #01: Reverse a Linked List works this problem in full, including the old trick behind it. This card is its one-page summary.
prev is the reversed front, head is the untouched rest, and between them they hold every node exactly once. A trace of a three node list:
start prev: none head: 1 2 3
step 1 prev: 1 head: 2 3
step 2 prev: 2 1 head: 3
step 3 prev: 3 2 1 head: none, so return prev
The solution
class ListNode:
def __init__(self, val=0, next=None): self.val, self.next = val, next
def build(a, h=None):
for v in reversed(a): h = ListNode(v, h)
return h
def to_list(h): return [h.val] + to_list(h.next) if h else []
def reverse_list(head):
prev = None
while head:
nxt = head.next # save the road before cutting it
head.next = prev # flip one arrow
prev, head = head, nxt
return prev
print(to_list(reverse_list(build([3, 1, 4, 1, 5]))))
print(to_list(reverse_list(build([8, 9]))))
print(to_list(reverse_list(build([]))))
[5, 1, 4, 1, 3]
[9, 8]
[]
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
nxt := head.Next // save the road before cutting it
head.Next = prev // flip one arrow
prev, head = head, nxt
}
return prev
}
Go needs a ListNode struct with Val and Next, plus a build and a toSlice helper. The same calls then print [5 1 4 1 3], [9 8], [].
Complexity
- Time O(n): each node is visited once and flipped once.
- Space O(1): three variables, no new nodes.
Traps
- Flipping the arrow before saving the next node.
head.next = prevfollowed byhead = head.nextwalks backwards, and[1, 2, 3]comes back empty. - Returning
headinstead ofprev. The loop ends whenheadis none, so every call answers none. - Writing it recursively in Python. A 5,000 node list, the largest the statement allows, passes the default limit of about 1,000 calls and raises
RecursionError.
Next in the ladder
Merge Two Sorted Lists rewires arrows again, but across two chains at once, with a dummy node holding the front of the result.