Arrays move items when their middle changes. A linked list changes connections instead. That can make a known insertion point cheap, but finding that point still takes time.
Save a link before replacing it
When reversing a list, changing current.next too early can lose the rest of the chain. Save the next node first, reverse the link, and only then move forward.
- previous points to the reversed part.
- current is the node being changed.
- next_node temporarily protects the untouched part.
Three pointers reverse the chain
def reverse(head):
previous = None
current = head
while current:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previousEach node is visited once, so reversal is O(n) time and O(1) extra space. The invariant is that previous always starts the correctly reversed section.
Drawing boxes and arrows is not childish—it is one of the best ways to debug link changes.
Your tiny challenge
Draw A pointing to B pointing to C. Reverse one arrow at a time and record previous, current, and next_node after every step.
