Sub topic 3
Walking the list in both directions
This chapter assumes you know Python classes and generators, how a singly linked list stores a next reference, and Big-O notation. It covers how the prev pointer lets you traverse a list from either end, and what can go wrong.
Why a second direction helps
In a singly linked list you can only move from head toward the end. To reach the node before a given node, you must start at the head and walk until node.next is the node you want. That costs O(n).
A doubly linked node stores both next and prev. The list also keeps a tail reference. With these, a traversal can start at either end and move in the matching direction.
Forward and backward generators
Both traversals use the same loop shape. Only the starting node and the pointer you follow change.
class Node:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def push_back(self, value):
node = Node(value)
node.prev = self.tail
if self.tail is not None:
self.tail.next = node
else:
self.head = node
self.tail = node
self.size += 1
return node
def __iter__(self):
node = self.head
while node is not None:
yield node.value
node = node.next
def reversed(self):
node = self.tail
while node is not None:
yield node.value
node = node.prev
lst = DoublyLinkedList()
for v in (1, 2, 3):
lst.push_back(v)
print(list(lst)) # [1, 2, 3]
print(list(lst.reversed())) # [3, 2, 1]Both methods are generators. They produce one value at a time and keep their place between yield calls. Each runs in O(n) time and uses O(1) extra memory. An empty list works without a special case. head and tail are both None, so the loop body never runs.
Walking from a node you already hold
Traversal does not have to start at an end. If you hold a node reference, you can walk in either direction from it. This is useful after a lookup, or when you keep node references yourself, as caches do.
def walk_back(node):
"""Yield values from node back to the head."""
while node is not None:
yield node.value
node = node.prev
last = lst.tail
print(list(walk_back(last))) # [3, 2, 1]
print(list(walk_back(last.prev))) # [2, 1]With a singly linked list, walk_back is impossible without the head. Here the node alone is enough.
Choosing the nearer end
The two directions give you a speedup for indexed access. To reach position i in a list of size nodes, start at the head if i < size / 2. Otherwise start at the tail and walk backward. The worst case drops from n steps to about n/2 steps. The complexity is still O(n), but the constant is halved.
Common errors
- Following
nextwhen you meantprev. The loop still ends, but it visits the wrong nodes. Name your loops clearly, as inreversedandwalk_backabove. - Starting the backward walk from
head.head.previsNone, so the loop stops after one node and no error is raised. - Changing the list while iterating. If you remove the current node inside the loop, its pointers may be cleared. Read
node.nextinto a local variable before you remove it. - Stale
tail. If an insert or remove forgets to updatetail,reversedstarts from the wrong node, or from a node that is no longer in the list.
Quick check of both directions
A cheap test is to compare the two traversals. The backward result should be the forward result reversed.
assert list(lst.reversed()) == list(lst)[::-1]You will build on this in a later chapter on pointer invariants.
Exercise
You hold a reference to a node in the middle of a doubly linked list of 1,000 nodes, and you need the value of the node two positions before it. How many steps does this take, and why can't a singly linked list do it as cheaply?
Show answer
It takes two steps: node.prev.prev.value, which is O(1). A singly linked list has no back pointer, so it must start from the head and walk forward until it reaches the node two positions before the one you hold. That is O(n).