Sub topic 11
Pointer invariants and how to test them
This chapter assumes you have read the earlier chapters on doubly and circular lists, so you know the DoublyLinkedList class with head, tail, size, push_front, push_back and remove. You also need basic Python assert statements and random.
What an invariant is
An invariant is a statement that must be true before and after every operation. In a linked list, most bugs are pointer updates that were skipped or done in the wrong order. An invariant check finds them right after the faulty operation. Without one, the damage often shows up much later as a crash or an endless loop.
Invariants of a doubly linked list
| Area | Invariant |
|---|---|
| Empty list | `head` is `None`, `tail` is `None`, and `size` is 0 |
| Ends | `head.prev` is `None` and `tail.next` is `None` |
| Links agree | For every node `n` with a successor, `n.next.prev is n` |
| Reachability | Walking `next` from `head` visits exactly `size` nodes and stops at `tail` |
The empty-list row matters most. If head is None while tail still points at an old node, later inserts take the wrong branch. That is the empty-list bug from the insertion chapter.
Writing the checker
The walk compares each node's prev with the node it just came from. This verifies every back pointer in one pass. The count check also stops the loop if a bug has created a cycle.
import random
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_front(self, value):
node = Node(value)
node.next = self.head
if self.head is not None:
self.head.prev = node
else:
self.tail = node
self.head = node
self.size += 1
return node
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 remove(self, node):
if node.prev is not None:
node.prev.next = node.next
else:
self.head = node.next
if node.next is not None:
node.next.prev = node.prev
else:
self.tail = node.prev
node.prev = None
node.next = None
self.size -= 1
def __iter__(self):
node = self.head
while node is not None:
yield node.value
node = node.next
def check_invariants(lst):
if lst.head is None or lst.tail is None:
assert lst.head is None and lst.tail is None, "one end is set, the other is None"
assert lst.size == 0, "empty list with nonzero size"
return
assert lst.head.prev is None, "head.prev must be None"
assert lst.tail.next is None, "tail.next must be None"
count = 0
last = None
node = lst.head
while node is not None:
assert node.prev is last, "prev does not match the previous node"
count += 1
assert count <= lst.size, "walk is longer than size (cycle or bad size)"
last = node
node = node.next
assert last is lst.tail, "forward walk does not end at tail"
assert count == lst.size, "size does not match node count"Testing with random operations
Hand-written tests tend to cover the cases you already thought of. A randomized test applies many operations and checks the invariants after each one. It also compares the list with a plain Python list that serves as a reference model.
def test_random_operations():
rng = random.Random(7)
lst = DoublyLinkedList()
model = [] # nodes in expected order
for _ in range(500):
op = rng.choice(["front", "back", "remove"])
if op == "remove" and model:
node = rng.choice(model)
lst.remove(node)
model.remove(node)
elif op == "front":
model.insert(0, lst.push_front(rng.randint(0, 99)))
else:
model.append(lst.push_back(rng.randint(0, 99)))
check_invariants(lst)
assert [n.value for n in model] == list(lst)
test_random_operations()
print("all checks passed")Because the generator is seeded, a failure reproduces on every run. Remove a node.next.prev = node.prev line from remove and the test fails within a few operations.
Invariants for the other variants
- Circular list with a tail reference: if
tailis notNone, followingnextexactlysizetimes must return totail. An empty list hastailset toNone. - Circular doubly list with a sentinel:
sentinel.next.prev is sentinelandsentinel.prev.next is sentinelalways hold. Each real node satisfiesn.next.prev is n. Walkingnextfrom the sentinel returns to it after exactlysizesteps.
Exercise
Suppose remove forgets the line node.next.prev = node.prev, so the successor still points back at the removed node. Which check in check_invariants fails, and why?
Show answer
The forward walk fails at the removed node's successor. Its prev still refers to the removed node, not to the node the walk came from, so node.prev is last is false. The assertion "prev does not match the previous node" fires.
Exercise
Write the invariant check for a CircularDoublyList with a sentinel. Which assertions do you need?
Show answer
Check sentinel.next.prev is sentinel and sentinel.prev.next is sentinel. Then walk next from sentinel.next, asserting node.prev is last (starting with last = sentinel) and that the count never exceeds size. Finally assert that the walk ends back at the sentinel and that the count equals size.