Reversing a list, one link at a time
🌍 In real life. Children play "rail-gari": each child holds the shoulders of the child in front, and the front child is the engine. To send the train the other way, go along from the engine, and let each child in turn let go and hold the child who was behind them instead. One rule keeps the game safe: before a child lets go, someone must remember who comes next, or the back half of the train wanders off and is lost.
Reversing a linked list is exactly this: turn every next link round, one at a time, without losing the rest.
The idea in one sentence: walk the list once with three markers, and at each node save the rest of the list, turn the node's link round to point backwards, and step on.
Its words:
- prev: the head of the part already reversed (None at the start)
- cur: the node being turned round
- nxt: the rest of the list, saved before
cur.nextchanges
How it works, step by step:
prev, cur = None, head- while cur:
nxt = cur.next(save),cur.next = prev(turn),prev = cur,cur = nxt(step on) - when cur is None,
previs the new head
Watch each link swing round under the row, with None moving from the right end to the left:
Why it is correct. Before every step two things are true: prev is the head of the nodes already visited, reversed, and cur is the head of the nodes not yet touched, still in their old order. A step moves one node, cur, from the front of the untouched part to the front of the reversed part, so both stay true. When the untouched part is empty (cur is None), every node is in the reversed part, and prev is its head. Saving nxt first is what keeps the untouched part reachable while cur's link points backwards.
What it costs. One pass, four assignments per node: O(n) time. Only three extra variables, whatever the length: O(1) extra memory. Copying the values into a Python list and building a new reversed linked list would also be O(n) time, but O(n) extra memory.
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def to_list(head): # given: the values, front to back
out = []
while head:
out.append(head.val)
head = head.next
return out
def reverse(head):
prev, cur = None, head
while cur:
nxt = cur.next # 1. save the rest
cur.next = prev # 2. turn this link round
prev = cur # 3. step on
cur = nxt
return prev # the old last node
head = Node(1, Node(2, Node(3, Node(4, Node(5)))))
head = reverse(head)
print(to_list(head))
print(to_list(reverse(None)), to_list(reverse(Node(7))))Mistakes and edge cases.
- not saving
nxtbeforecur.next = prev: after that line,cur.nextis the reversed part, so the rest of the list is lost - returning
head: after reversing, the old head is the last node, so you get a list of one node; returnprev - forgetting that the old head's next must become None: starting with
prev = Nonedoes that - an empty list and a one-node list reverse to themselves, with no special code
Quiz
What does this print?
class Node: def __init__(self, val, next=None): self.val = val self.next = next head = Node(6, Node(7, Node(8))) prev, cur = None, head while cur: nxt = cur.next cur.next = prev prev, cur = cur, nxt print(prev.val, prev.next.val, head.next)This gives back a list of one node instead of the whole list reversed. Which line is wrong?
def reverse(head): prev, cur = None, head while cur: cur.next = prev prev = cur cur = cur.next return prevAfter the loop ends, which marker is the new head?
- prev
- cur
- head
How much extra memory does reversing in place need for n nodes?
- O(1): three markers
- O(n): a copy of the values
- O(n²)
Coding tasks
Write
reverse(head): reverse the linked list in place by turning its links round, and give back the new head.Write
reverse_first(head, k): reverse only the first k nodes and keep the rest after them in order (if k is at least the length, reverse it all; k = 0 changes nothing). Give back the new head.