Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 1

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

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:

  1. Uniform O(1) ring invariant: self.head.next always points to the first real node (or self.head when empty), and self.head.prev always points to the last real node (or self.head when empty). Because live links never contain None, every insertion and unlinking step runs in O(1) without special-case branches.
  2. 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 cur and cur.prev.next is cur), so walking backward from self.head.prev always 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.

Terminal · create lab workspace
mkdir dll-lab && cd dll-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pytest hypothesis

02. 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?

Text · splicing fresh between node and nxt inside insert_after
Before:  [node] <===========> [nxt]        (save nxt = node.next)

After:   [node] <===> [fresh] <===> [nxt]  (set fresh, node.next, nxt.prev)
Python · dll.py
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)
Terminal
python dll.py
Expected output
initial: [5, 10, 20] len= 3
after unlink(10): [5, 20] len= 2
after unlink(20): [5] head.next.val= 5

After 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.

04. Check your understanding

Practice check · 2 questions

Sentinel ring invariants

Spot subtle pointer and equality bugs in doubly linked lists.

Q1. `DNode` uses default `@dataclass` (comparing `val`, `prev`, `next`). If `__iter__` writes `while cur != self.head:` on a 1-node list holding `val = 0`, what happens?
Q2. In `SentinelDoublyLinkedList` (`append` calls `insert_after(self.head.prev, val)`), someone writes `node.next = DNode(val, prev=node, next=node.next)` and omits `nxt.prev = fresh`. After `dll.append(10)` and `dll.append(20)`, what does `list(dll)` return?
Practice only: not graded, not saved, not evidence.

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:

  1. How do append(val) and prepend(val) reuse insert_after in SentinelDoublyLinkedList?
  2. Why must check_ring_invariants test both cur.next.prev is cur and cur.prev.next is cur instead of only asserting list(dll) == model?
  3. Write out the four link updates in insert_after(node, val) and explain why nxt = node.next must come first.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check