Reverse a linked list
Picture
At A→B→C, changing A.next to None before saving B would lose access to B and C.
Predict
Which reference must be saved before changing current.next?
Walk through the small example
The old next node. A three-reference invariant preserves both the reversed prefix and untouched suffix.
Mental model and complete Python solution
Draw a boundary. Everything left of it already points backward; everything right still points forward. Move exactly one node across without losing the right side.
What the function promises: Return the new head after reversing an acyclic singly linked list.
class Node:
def __init__(self, value, next_node=None):
self.value, self.next = value, next_node
def build(values):
head = None
for value in reversed(values):
head = Node(value, head)
return head
def to_list(head):
answer = []
while head is not None:
answer.append(head.value)
head = head.next
return answer
def reverse_list(head):
previous, current = None, head
while current is not None:
following = current.next
current.next = previous
previous, current = current, following
return previous
head = build([1,2,3])
assert to_list(reverse_list(head)) == [3,2,1]
assert reverse_list(None) is None
Work and storage: O(n) time and O(1) extra space.
When to recognize it: A three-reference invariant preserves both the reversed prefix and untouched suffix.
Check before applying it: Rewiring before saving next loses the remainder; cycles require a different contract.
Change one rule
Reverse nodes in groups of k.
See what changes
Protect the node after each group, reverse exactly k nodes, then connect the previous group tail and remaining suffix.
Connect
Linked lists: follow references: Use named references to protect reachability.
Linked List Cycle: Both algorithms extract structure with constant pointer state.