Sub topic 8
Reversing a list in place
This chapter assumes you can build a singly linked list with Node objects and a head reference, and that you can traverse one with a while loop. You should also know introductory Big-O notation. Here you will reverse a list by rewiring its links instead of copying its values.
What "in place" means
Reversing a list means that the node that was last becomes first, and every node points to the node that used to precede it. "In place" means you do this by changing the next references of the existing nodes. You do not build a second list.
A copy-based approach would walk the list, collect the values, and build new nodes in the opposite order. That costs O(n) extra memory. The in-place approach uses only a few local variables, so the extra space is O(1). Time is O(n) either way, because every node must be visited at least once.
The in-place version has a second advantage. Any other code that holds a reference to a node still sees the same node object, now with a different next.
The three-variable loop
The core idea is to walk the list once. At each node you flip its next reference so that it points backward. Flipping a reference destroys the only link to the rest of the list, so you must save that link first.
The loop uses three variables:
previs the node just behindcurrent. It starts asNone, because the new last node must point to nothing.currentis the node you are processing. It starts athead.nxtis a saved copy ofcurrent.next, taken before you overwrite it.
Each iteration performs four steps, and their order matters:
- Save the next node:
nxt = current.next. - Point the current node backward:
current.next = prev. - Advance
prevto the current node. - Advance
currentto the saved next node.
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
def from_values(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head):
out = []
while head is not None:
out.append(head.value)
head = head.next
return out
head = from_values([1, 2, 3, 4])
print(to_list(head)) # [1, 2, 3, 4]
head = reverse(head)
print(to_list(head)) # [4, 3, 2, 1]The function returns prev, not head. When the loop ends, current is None and prev is the old last node. That node is the new first node, so it is the new head.
Tracing the loop
Here is the loop run on the list 1, 2, 3. Each row shows the state after the iteration finishes.
| Iteration | `nxt` saved | Link changed | `prev` | `current` |
|---|---|---|---|---|
| start | none | none | `None` | node 1 |
| 1 | node 2 | 1 now points to `None` | node 1 | node 2 |
| 2 | node 3 | 2 now points to 1 | node 2 | node 3 |
| 3 | `None` | 3 now points to 2 | node 3 | `None` |
The loop stops because current is None. Node 3 is the head of the reversed list, and following its links gives 3, 2, 1.
A useful way to reason about this is the loop invariant. At the start of every iteration, prev is the head of a correctly reversed list made of the nodes already processed. current is the head of the untouched remainder. Each iteration moves one node from the remainder onto the front of the reversed part. When the remainder is empty, the reversed part is the whole list.
Edge cases
The same code handles the small cases without special branches:
- An empty list:
headisNone, the loop never runs, andprevis stillNone. The result is an empty list. - A one-node list: the loop runs once. The node's
nextis set toNone, which it already was, andprevis that node. - A two-node list: the loop runs twice, and the two nodes swap roles.
This is why the initial value of prev matters. Starting it at None makes the old head become the new tail with next set to None. You do not need to clear it separately.
Using it from a list class
If your list class stores head, the method must assign the return value back. Otherwise the list still points at its old first node, which is now the last.
class LinkedList:
def __init__(self):
self.head = None
def push_front(self, value):
self.head = Node(value, self.head)
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
def reverse(self):
self.head = reverse(self.head)
items = LinkedList()
for v in (3, 2, 1):
items.push_front(v)
print(list(items)) # [1, 2, 3]
items.reverse()
print(list(items)) # [3, 2, 1]Common mistakes
Most reversal bugs come from a small set of errors:
- Overwriting
current.nextbefore saving it. If you writecurrent.next = prevfirst, the rest of the list is unreachable and the loop stops after one node. Always savenxtfirst. - Returning
head. After reversal, the original head is the tail. ItsnextisNone, so you get a one-element list. - Starting
prevathead. This creates a cycle between the first two nodes, and any later traversal loops forever. - Reordering the advance steps. If you move
current = current.nextafter you have already pointedcurrent.nextbackward, you step back to the previous node instead of forward.
A recursive version
You can also express reversal recursively. The function reverses everything after the head, then attaches the head to the end of that reversed part.
def reverse_recursive(head):
if head is None or head.next is None:
return head
new_head = reverse_recursive(head.next)
head.next.next = head
head.next = None
return new_headAfter the recursive call, head.next is still the node that is now the tail of the reversed remainder. Setting head.next.next = head appends head after it. Setting head.next = None makes head the new tail.
This version is correct and shows the structure of the problem well. In practice, prefer the iterative loop for two reasons:
- It uses O(n) call-stack space, not O(1).
- Python's default recursion limit is about 1000 frames, so a list of a few thousand nodes raises
RecursionError.
Reversing only part of a list
A common variation is to reverse the nodes from position left to position right (1-indexed) and leave the rest alone. The inner loop is the same one you just learned. The new work is reconnecting the reversed section to the nodes on either side.
A dummy node in front of the head removes the special case where left is 1. In that case the head itself changes. The function below assumes 1 <= left <= right <= length.
def reverse_between(head, left, right):
dummy = Node(None, head)
before = dummy
for _ in range(left - 1):
before = before.next
prev = None
current = before.next
for _ in range(right - left + 1):
nxt = current.next
current.next = prev
prev = current
current = nxt
# before.next is still the original left node, now the tail of the section.
before.next.next = current # attach the tail to the first node after the section
before.next = prev # attach the new section head after `before`
return dummy.next
head = from_values([1, 2, 3, 4, 5])
head = reverse_between(head, 2, 4)
print(to_list(head)) # [1, 4, 3, 2, 5]The two final assignments must run in this order. The first uses before.next, which still refers to the original left node. The second then replaces before.next with the new section head. Swapping them would lose the reference to the section's tail.
Cost summary
| Version | Time | Extra space | Notes |
|---|---|---|---|
| Iterative, in place | O(n) | O(1) | Preferred. No depth limit. |
| Recursive | O(n) | O(n) | Hits the recursion limit on long lists. |
| Copy values into new nodes | O(n) | O(n) | Leaves the original nodes untouched. |
| Reverse a sublist | O(n) | O(1) | Time is dominated by walking to `left` and through the section. |
Checking your work
When you write list code, test the small cases first: empty, one node, and two nodes. Then compare against a plain Python list. For any input values, to_list(reverse(from_values(values))) should equal values[::-1].
import random
for _ in range(200):
values = [random.randint(0, 9) for _ in range(random.randint(0, 8))]
assert to_list(reverse(from_values(values))) == values[::-1]
print("all checks passed")Exercise
In the iterative reversal loop, suppose you swap the first two lines of the loop body so that it reads current.next = prev and then nxt = current.next. What happens when you run it on the list 1, 2, 3, and why?
Show answer
After current.next = prev, the link to the rest of the list is lost, so nxt receives the value of prev, which is None on the first iteration. The loop then sets prev to node 1 and current to None, and it ends. The function returns node 1, whose next is None. The result is the one-element list [1], and nodes 2 and 3 are unreachable. The fix is to save nxt = current.next before overwriting current.next.
Exercise
Using reverse_between as written, what list does reverse_between(from_values([1, 2, 3, 4, 5]), 1, 3) produce, and why does the dummy node matter in this case?
Show answer
It produces [3, 2, 1, 4, 5]. Here left is 1, so the section starts at the head. The loop that moves before runs zero times, so before is the dummy node. Setting before.next = prev makes the dummy point to the new section head, and returning dummy.next gives the correct new head. Without the dummy node, you would need a separate branch to update the list head.