Nodes, References and Sentinels
Contrast pointer-linked nodes with contiguous arrays, see why sentinel nodes eliminate head and empty-list edge cases, and compare singly, doubly and circular linked lists.
Contentsand lesson path
On this page
- Why it matters
- Singly, doubly and circular linked nodes
- How a sentinel eliminates head and empty-list branches
- 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. Why it matters
In How a Python List Grows, you saw why Python list forces O(n) pointer shifts whenever you insert or remove near index 0, and even removing a middle slot shifts every later element left. Suppose your program holds a direct handle to an active item in the middle of an ordered sequence—such as a cached entry tracked in a dict or a scheduled task in a timer queue—and needs to detach or move that item in strict O(1) time without shifting neighbours.
A linked list gives up contiguous memory and O(1) integer indexing so that adjacent elements connect purely through object references (memory addresses pointing from one heap object to the next). Yet pointer-based structures carry a notorious trap: most bugs in linked-list code happen at boundary cases—an empty list (head is None), the first node (head), or the last node (tail). Adding a single dummy sentinel node turns every boundary case into the ordinary middle case.
02. Singly, doubly and circular linked nodes
Instead of packing element references into one contiguous array buffer, a linked list wraps each value inside its own Node object holding a payload (val) and one or two reference attributes:
- Singly linked node: stores
valandnext. Splicing a new node after a known nodeprevtakesO(1)(fresh.next = prev.next; prev.next = fresh) because you only reassign two attributes. However, if a caller hands you only a reference to a middle nodexand asks you to removex, you cannot unlinkxinO(1)time: unlinkingxmeans rewiring its predecessor (prev.next = x.next), andxholds no backward link, so locatingprevrequires walking fromheadinO(n)time. - Doubly linked node: adds a
prevreference alongsidenext. Given only nodex, you can readx.prevandx.nextdirectly and unlinkxinO(1)time (x.prev.next = x.nextandx.next.prev = x.prev) without scanning fromheador knowing the list length. - Circular linked list: connects the last node back to the front instead of terminating with
None. In a circular singly linked list holding a singletailpointer (tail.nextishead), you can prepend aftertail(fresh.next = tail.next; tail.next = fresh) and append attail(tail = fresh) both inO(1)—yet popping the tail still costsO(n)because there are noprevlinks. In a circular doubly linked list with a sentinel, even an empty list closes cleanly onto itself (head.next is headandhead.prev is head).
Simplification boundary: diagrams below draw tidy arrows between boxes ([10] -> [20] -> None). In real CPython memory, each Node is a separate heap-allocated object carrying Python object headers, a reference count, and storage for its attributes (CPython 3.11+ keeps them inline and builds a __dict__ only on demand; __slots__ shrinks it further), giving much worse CPU cache locality during sequential scans than a flat Python list whose 8-byte pointers sit side by side.
Singly linked with sentinel (removes head=None branch):
[sentinel] ---> [10] ---> [20] ---> [30] ---> None
^
prev starts here, so deleting [10] matches deleting [30]
Circular doubly linked with sentinel (every real node has prev and next):
+---> [SENTINEL] <===> [10] <===> [20] <---+
|__________________________________________|03. How a sentinel eliminates head and empty-list branches
Consider deleting the first node matching target in a singly linked list without a sentinel. You must write a guard for head is None, a second branch for head.val == target (returning head.next because reassigning a local parameter head never updates the caller's variable), and a third loop for interior nodes where prev.next is checked. Every time you refactor that function, it is easy to break only the head or 1-element branch.
Wrapping the input chain behind a temporary dummy node sentinel = SNode(0, head) establishes one simple invariant: every real node in the list has a non-None predecessor (prev), starting with sentinel itself for the first real node (sentinel.next). Because prev begins at sentinel, deleting 10 (the head), 30 (the tail), or 50 (the sole element) executes the exact same line prev.next = prev.next.next. Returning sentinel.next at the end hands back the updated head—including None if the list was empty or became empty.
Predict before reading the output: trace remove_value_with_sentinel(SNode(50), 50) and remove_value_with_sentinel(None, 10) by hand. In the single-node call, what does sentinel.next become after prev.next = prev.next.next, and why does the dummy value 0 never appear in to_list?
from dataclasses import dataclass
@dataclass
class SNode:
val: int
next: "SNode | None" = None
def to_list(head: SNode | None) -> list[int]:
out: list[int] = []
cur = head
while cur is not None:
out.append(cur.val)
cur = cur.next
return out
def remove_value_with_sentinel(head: SNode | None, target: int) -> SNode | None:
sentinel = SNode(0, head)
prev = sentinel
while prev.next is not None:
if prev.next.val == target:
prev.next = prev.next.next
break
prev = prev.next
return sentinel.next
chain = SNode(10, SNode(20, SNode(30)))
print("before:", to_list(chain))
chain = remove_value_with_sentinel(chain, 10)
print("after removing 10 (head):", to_list(chain))
chain = remove_value_with_sentinel(chain, 30)
print("after removing 30 (tail):", to_list(chain))
chain = remove_value_with_sentinel(chain, 99)
print("after removing 99 (missing):", to_list(chain))
print("single [50] remove 50:", to_list(remove_value_with_sentinel(SNode(50), 50)))
print("empty remove 10:", to_list(remove_value_with_sentinel(None, 10)))before: [10, 20, 30]
after removing 10 (head): [20, 30]
after removing 30 (tail): [20]
after removing 99 (missing): [20]
single [50] remove 50: []
empty remove 10: []In the single-node call remove_value_with_sentinel(SNode(50), 50), prev starts at sentinel, sees prev.next.val == 50, sets sentinel.next = None, and returns sentinel.next (None), so to_list prints []. And when head is None, prev.next is immediately None, so the while loop runs zero times and returns None without an extra if head is None: check. Because we return sentinel.next rather than sentinel, the temporary dummy object 0 stays discarded and never leaks into the caller's list.
Keeping an explicit tail pointer alongside head on a singly linked list lets you append after tail in O(1) (tail.next = fresh; tail = fresh, updating tail if the list was empty), yet still cannot remove tail in O(1) because finding the predecessor before tail still walks from head. Only adding prev links (making the list doubly linked) makes unlinking any known node—including tail—strictly O(1).
Trade-off of sentinels: a sentinel adds one dummy Node allocation (O(1) extra memory) and requires discipline never to expose, yield, or unlink the sentinel itself. For recursive singly linked algorithms (which you will explore in Recursion & Divide and Conquer), passing bare Node | None is usually cleaner; for iterative mutations and doubly linked rings, a sentinel removes nearly every boundary bug.
When not to use a linked list: whenever your workload indexes by position (seq[k]), iterates repeatedly over sequential values, or only pushes and pops at the ends, Python list and collections.deque use far less memory per element and avoid per-node Python object overhead—a trade-off whose per-node memory cost and front-pop speed we measure in Lists, Arrays or Deques?.
04. Check your understanding
05. Apply it
Build a small SinglyLinkedList class backed by a sentinel self.head = SNode(0) with insert_after(node: SNode, val: int) -> SNode, delete_after(node: SNode) -> int (raising ValueError when node.next is None), and to_list() -> list[int]. Write tests covering inserting after self.head (empty list and front insert), inserting after an interior node, deleting the first and sole real nodes, and confirming delete_after raises ValueError at the tail. Also update remove_value_with_sentinel to remove every matching node—advancing prev only in an else branch so consecutive matches such as [10, 10, 20] are not skipped.
Next, build a full circular doubly linked list and test its invariants with Hypothesis in Lab: A Doubly Linked List with a Sentinel.
06. Review prompt
Without looking back:
- Why does holding only a reference to middle node
xallowO(1)deletion in a doubly linked list, yet requireO(n)in a singly linked list—even if the singly list keeps atailpointer? - What structural invariant does a sentinel node guarantee for every real node in a list?
- Name one advantage of a linked list over Python
listand one reason Pythonlistusually beats it.
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.