Reverse a Linked List
Linked Lists: lesson 4 of 6
Flip every arrow backwards using three pointers.
Lesson 4 of 6 · 5 min
Reverse a Linked List
Step 1 of 11
node
prev
nxt
head
·
1•
·
2•
·
3•
∅
∅
Three pointers: prev trails (it starts at ∅), node is current, and a temporary saves the rest of the chain.
The Idea
Walk the list once, turning each link to face the node behind it. Three pointers do the work: prev trails, node is current, and a temporary holds the rest of the chain before you overwrite it. The old tail becomes the new head.
Real-World Example
A bucket brigade reversing direction after the fire is out. Nobody changes places; each person simply turns to face the neighbour they used to receive from. The last person in the chain is suddenly the one who starts every pass.
The Code
class Node:
def __init__(self, v): self.value, self.next = v, None
def reverse(head):
prev, node = None, head
while node:
nxt = node.next # remember the rest of the list
node.next = prev # flip this link backwards
prev, node = node, nxt # slide both pointers forward
return prev # the old tail is the new head
head = Node(1); head.next = Node(2); head.next.next = Node(3)
node = reverse(head)
while node: # prints 3 2 1
print(node.value, end=" "); node = node.next
Your turn
What does this print?
class Node:
def __init__(self, v): self.value, self.next = v, None
a = Node(1); a.next = Node(2)
prev = None
while a:
nxt = a.next
a.next = prev
prev, a = a, nxt
print(prev.value, prev.next.value)Mini quiz
1 / 3