Lab: A Doubly Linked List with a Sentinel
Build a circular sentinel doubly linked list supporting O(1) append, prepend, insert_after and unlink, predict unlink state, and test bidirectional invariants with Hypothesis.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: implement SentinelDoublyLinkedList and predict unlink state
- Step 2: verify forward and backward invariants with Hypothesis
- Check your understanding
- Apply it
- Review prompt
Lessons of Linked Lists
- Nodes, References and Sentinels Concept · 20 min
- Lab: A Doubly Linked List with a Sentinel Lab · 30 min
- Reference Surgery: Reverse, Merge, Split Worked example · 25 min
- Two Speeds Through One List Worked example · 20 min
- Lists, Arrays or Deques? Concept · 15 min
- Check: Linked List Exercises Knowledge check · 8 questions
What you will learn
- Implement singly and doubly linked lists with a sentinel node, supporting O(1) insertion and deletion at a known node.
Prerequisites: Complexity Analysis
01. Goal and setup
In Nodes, References and Sentinels, you saw on paper how a circular sentinel unifies head, tail, middle, and empty-list logic. Without a circular sentinel, every insertion or removal in a doubly linked list must branch on head is None, node is head, and node is tail—and missing just one branch leaves a stale prev or next reference that corrupts a later operation.
In this lab you build SentinelDoublyLinkedList in Python and test two structural invariants across random sequences of append, prepend, insert_after, and unlink:
- Uniform
O(1)ring invariant:self.head.nextalways points to the first real node (orself.headwhen empty), andself.head.prevalways points to the last real node (orself.headwhen empty). Because live links never containNone, every insertion and unlinking step runs inO(1)without special-case branches. - Bidirectional symmetry invariant: forward links (
next) and backward links (prev) mirror each other at every node in the ring, including the sentinel (cur.next.prev is curandcur.prev.next is cur), so walking backward fromself.head.prevalways yields the reverse of walking forward.
Simplification note: SentinelDoublyLinkedList stores int payloads and returns DNode handles from append, prepend, and insert_after so callers can pass a handle directly to unlink in O(1). A production container would also record an owner tag on each node so unlink rejects a DNode belonging to a different list instance.
Environment: verified with Python 3.12.13, pytest 9.2.0, and hypothesis 6.170.17 inside a fresh virtual environment.
mkdir dll-lab && cd dll-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pytest hypothesis02. Step 1: implement SentinelDoublyLinkedList and predict unlink state
Create dll.py. In __init__, the sentinel self.head points both .prev and .next to itself so the empty ring starts closed. Both prepend and append delegate directly to insert_after: prepend inserts right after self.head, and append inserts right after self.head.prev (which is the last real node, or self.head itself when the list is empty).
Trace the four link updates inside insert_after(node, val): first save nxt = node.next, then create fresh = DNode(val, prev=node, next=nxt), then set node.next = fresh and nxt.prev = fresh. Saving nxt = node.next before assigning node.next = fresh is essential because overwriting node.next first would lose your handle to nxt. Notice also that insert_after and unlink check if node.prev is None or node.next is None: raise ValueError(...) explicitly rather than relying on assert (which python -O strips out), and unlink forbids removing self.head.
When unlink(node) succeeds, it clears node.prev = None and node.next = None before returning node.val. Clearing detached links ensures that accidentally unlinking the same node twice fails immediately with ValueError instead of splicing stale neighbours. Keeping self._size updated on every insertion and removal also keeps len(dll) at O(1) rather than walking the whole ring; if you forgot self._size -= 1 inside unlink, the links themselves would stay intact while len(dll) drifted out of sync with list(dll).
Predict before running: in __main__, dll appends 10 (n1), appends 20 (n2), prepends 5, then unlinks n1 (10) and n2 (20). What is head.next.val at the end, and what would dll.head.prev equal if you unlinked 5 as well?
Before: [node] <===========> [nxt] (save nxt = node.next)
After: [node] <===> [fresh] <===> [nxt] (set fresh, node.next, nxt.prev)from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class DNode:
val: int
prev: "DNode | None" = None
next: "DNode | None" = None
class SentinelDoublyLinkedList:
def __init__(self) -> None:
self.head = DNode(0)
self.head.prev = self.head
self.head.next = self.head
self._size = 0
def __len__(self) -> int:
return self._size
def insert_after(self, node: DNode, val: int) -> DNode:
if node.next is None or node.prev is None:
raise ValueError("cannot insert after an unlinked node")
nxt = node.next
fresh = DNode(val, prev=node, next=nxt)
node.next = fresh
nxt.prev = fresh
self._size += 1
return fresh
def append(self, val: int) -> DNode:
assert self.head.prev is not None
return self.insert_after(self.head.prev, val)
def prepend(self, val: int) -> DNode:
return self.insert_after(self.head, val)
def unlink(self, node: DNode) -> int:
if node is self.head:
raise ValueError("cannot unlink sentinel node")
if node.prev is None or node.next is None:
raise ValueError("node is not linked")
node.prev.next = node.next
node.next.prev = node.prev
node.prev = None
node.next = None
self._size -= 1
return node.val
def __iter__(self) -> Iterator[int]:
cur = self.head.next
while cur is not None and cur is not self.head:
yield cur.val
cur = cur.next
if __name__ == "__main__":
dll = SentinelDoublyLinkedList()
n1 = dll.append(10)
n2 = dll.append(20)
dll.prepend(5)
print("initial:", list(dll), "len=", len(dll))
dll.unlink(n1)
print("after unlink(10):", list(dll), "len=", len(dll))
dll.unlink(n2)
nxt = dll.head.next
nxt_val = nxt.val if nxt is not None and nxt is not dll.head else None
print("after unlink(20):", list(dll), "head.next.val=", nxt_val)python dll.pyinitial: [5, 10, 20] len= 3
after unlink(10): [5, 20] len= 2
after unlink(20): [5] head.next.val= 5After unlinking 10 (middle) and 20 (tail), 5 remains (head.next.val= 5). Both unlink(n1) and unlink(n2) ran the exact same two rewiring lines with zero if branches for middle vs tail. If you unlinked 5 as well, 5.prev (self.head) would set self.head.next = self.head and 5.next (self.head) would set self.head.prev = self.head, returning the ring cleanly to empty.
03. Step 2: verify forward and backward invariants with Hypothesis
A subtle pointer bug often leaves next links looking valid locally while prev links point to a stale node. Because append calls insert_after(self.head.prev, val), forgetting nxt.prev = fresh inside insert_after leaves self.head.prev stuck pointing at self.head: every append lands at the front, so append(10), append(20), and prepend(5) print [5, 20, 10] instead of [5, 10, 20]—and unlinking 20 (whose stale prev is self.head) drops 5 and leaves [10]! Hypothesis catches that asymmetry on the very first append.
To catch asymmetric link bugs immediately, test_dll.py defines check_ring_invariants(dll): it walks len(dll) + 1 forward hops from dll.head, asserts cur.next.prev is cur and cur.prev.next is cur at every node, confirms that the loop returns to dll.head after exactly len(dll) + 1 steps (catching any lost node, short internal cycle, or _size drift), and walks backward from dll.head.prev to verify backward == list(reversed(forward)). Our Hypothesis test drives random sequences of append, prepend, insert_after, and unlink against a plain Python list model and checks every invariant after each operation; whenever a pointer bug breaks an invariant on a long random sequence, Hypothesis automatically shrinks the failing input down to a short, often 1- or 2-step, reproduction. A second test, test_unlink_guards, verifies that unlinking dll.head or an already-detached node raises ValueError.
Notice why __iter__ and check_ring_invariants write cur is not self.head instead of cur != self.head: default @dataclass generates a recursive field-by-field __eq__, so comparing two linked DNode objects with == or != can recurse along prev and next around the circular ring until Python hits RecursionError (for example, a 1-node ring whose val equals the sentinel's 0)! Create test_dll.py and run pytest.
import pytest
from hypothesis import given
from hypothesis import strategies as st
from dll import DNode, SentinelDoublyLinkedList
def check_ring_invariants(dll: SentinelDoublyLinkedList) -> None:
forward: list[int] = []
cur: DNode | None = dll.head
for _ in range(len(dll) + 1):
assert cur is not None and cur.next is not None and cur.prev is not None
assert cur.next.prev is cur
assert cur.prev.next is cur
if cur is not dll.head:
forward.append(cur.val)
cur = cur.next
assert cur is dll.head
backward: list[int] = []
cur = dll.head.prev
while cur is not None and cur is not dll.head:
backward.append(cur.val)
cur = cur.prev
assert list(dll) == forward
assert backward == list(reversed(forward))
@given(
st.lists(
st.tuples(
st.sampled_from(["append", "prepend", "insert_mid", "unlink"]),
st.integers(-50, 50),
),
max_size=50,
)
)
def test_dll_invariants_against_model(ops: list[tuple[str, int]]) -> None:
dll = SentinelDoublyLinkedList()
handles: list[DNode] = []
model: list[int] = []
for op, val in ops:
if op == "append":
handles.append(dll.append(val))
model.append(val)
elif op == "prepend":
handles.insert(0, dll.prepend(val))
model.insert(0, val)
elif op == "insert_mid" and handles:
pos = abs(val) % len(handles)
handles.insert(pos + 1, dll.insert_after(handles[pos], val))
model.insert(pos + 1, val)
elif op == "unlink" and handles:
pos = abs(val) % len(handles)
node = handles.pop(pos)
assert dll.unlink(node) == model.pop(pos)
check_ring_invariants(dll)
assert list(dll) == model
assert len(dll) == len(model)
def test_unlink_guards() -> None:
dll = SentinelDoublyLinkedList()
node = dll.append(42)
with pytest.raises(ValueError):
dll.unlink(dll.head)
assert dll.unlink(node) == 42
with pytest.raises(ValueError):
dll.unlink(node)
check_ring_invariants(dll)pytest -v test_dll.pycollecting ... collected 2 items
test_dll.py::test_dll_invariants_against_model PASSED [ 50%]
test_dll.py::test_unlink_guards PASSED [100%]04. Check your understanding
05. Apply it
Add a reverse_iter() generator walking backward from self.head.prev to self.head and a pop_front() -> int helper that unlinks self.head.next (raising IndexError when empty). Switch DNode to @dataclass(eq=False) so two nodes never trigger recursive equality, and add test_pop_front_and_reverse_iter to test_dll.py asserting that repeated pop_front() drains the ring cleanly.
Next, apply reference rewiring to singly linked list transformations in Reference Surgery: Reverse, Merge, Split.
06. Review prompt
Without looking back:
- How do
append(val)andprepend(val)reuseinsert_afterinSentinelDoublyLinkedList? - Why must
check_ring_invariantstest bothcur.next.prev is curandcur.prev.next is curinstead of only assertinglist(dll) == model? - Write out the four link updates in
insert_after(node, val)and explain whynxt = node.nextmust come first.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.