Sub topic 8
Reversing a list in place
This chapter assumes you can write the Node and LinkedList classes from earlier chapters, that you can traverse a list with a while loop, and that you know O(n) and O(1) notation. You will learn how to reverse a singly linked list by changing its links, without copying any values.
The idea
Reversing a list means every node's next reference must point at the node that used to come before it. The values stay where they are in memory. Only the references change.
A singly linked node has no prev reference, so you cannot walk backwards. Instead, you walk forward once and flip each link as you pass it. This needs three references:
previs the already reversed part of the list. It starts asNone.currentis the node you are working on. It starts at the head.nxtis a saved copy ofcurrent.next, so you do not lose the rest of the list.
The code
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def reverse(head):
prev = None
current = head
while current is not None:
nxt = current.next
current.next = prev
prev = current
current = nxt
return prev
head = Node(1, Node(2, Node(3)))
head = reverse(head)
node = head
while node is not None:
print(node.value)
node = node.nextThis prints 3, 2, 1, one per line. Each loop pass does four steps in a fixed order:
- Save the next node:
nxt = current.next. - Point the current node backwards:
current.next = prev. - Move
prevforward to the current node. - Move
currentforward to the saved node.
The function returns prev because when the loop ends, current is None and prev is the old last node. That node is the new head.
Tracing it
Here is the state of the list 1 -> 2 -> 3 after each pass.
After pass one, node 1 points to None. After pass two, node 2 points to node 1. After pass three, node 3 points to node 2. The chain is now 3 -> 2 -> 1.
Cost
The loop visits each node once and does a fixed amount of work per node, so the time is O(n). It uses three references no matter how long the list is, so the extra space is O(1). A recursive version also runs in O(n) time, but it uses O(n) stack space and can hit Python's recursion limit on long lists.
Common errors
- Forgetting to save
current.next. If you writecurrent.next = prevfirst, you lose the rest of the list. Always savenxtbefore changing the link. - Ignoring the return value. The old head is now the tail. If you keep using the old
headvariable, you see a list with only one node. Assign the result:head = reverse(head). - Returning
currentinstead ofprev. At the end of the loop,currentisNone. - Not handling the empty list. The code above already handles it. With
head = None, the loop does not run and the function returnsNone.
Exercises
Exercise
What are the time and extra space costs of the iterative reverse, and why does the function return prev instead of current?
Show answer
Time is O(n) because each node is visited once. Extra space is O(1) because only prev, current, and nxt are stored. It returns prev because the loop ends when current is None, and at that point prev holds the old last node, which is the new head.
Exercise
A learner removes the line nxt = current.next and writes current = current.next at the end of the loop instead. What goes wrong?
Show answer
By then current.next has already been set to prev, so current moves backwards to the previous node. The loop goes back to the node it just handled and never reaches the rest of the list. The original next node must be saved before the link is changed.