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 1 of 6 · Concept · 20 min · revision 1

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

  1. Why it matters
  2. Singly, doubly and circular linked nodes
  3. How a sentinel eliminates head and empty-list branches
  4. Check your understanding
  5. Apply it
  6. Review prompt

Lessons of Linked Lists

  1. Nodes, References and Sentinels Concept · 20 min
  2. Lab: A Doubly Linked List with a Sentinel Lab · 30 min
  3. Reference Surgery: Reverse, Merge, Split Worked example · 25 min
  4. Two Speeds Through One List Worked example · 20 min
  5. Lists, Arrays or Deques? Concept · 15 min
  6. 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 val and next. Splicing a new node after a known node prev takes O(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 node x and asks you to remove x, you cannot unlink x in O(1) time: unlinking x means rewiring its predecessor (prev.next = x.next), and x holds no backward link, so locating prev requires walking from head in O(n) time.
  • Doubly linked node: adds a prev reference alongside next. Given only node x, you can read x.prev and x.next directly and unlink x in O(1) time (x.prev.next = x.next and x.next.prev = x.prev) without scanning from head or 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 single tail pointer (tail.next is head), you can prepend after tail (fresh.next = tail.next; tail.next = fresh) and append at tail (tail = fresh) both in O(1)—yet popping the tail still costs O(n) because there are no prev links. In a circular doubly linked list with a sentinel, even an empty list closes cleanly onto itself (head.next is head and head.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.

Text · singly list with sentinel vs circular doubly linked sentinel
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?

Python · uniform singly linked removal using a sentinel node
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)))
Expected output
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

Practice check · 2 questions

Nodes, links and sentinels

Check pointer requirements for singly, circular and doubly linked lists.

Q1. A singly linked list stores both `head` and `tail` pointers (no `prev` links). Which set of operations can it run in `O(1)` without scanning from `head`?
Q2. In a circular doubly linked list with sentinel `H` (initially `H.next = H` and `H.prev = H`), you insert one node `X` after `H`. What are `X.prev` and `X.next`?
Practice only: not graded, not saved, not evidence.

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:

  1. Why does holding only a reference to middle node x allow O(1) deletion in a doubly linked list, yet require O(n) in a singly linked list—even if the singly list keeps a tail pointer?
  2. What structural invariant does a sentinel node guarantee for every real node in a list?
  3. Name one advantage of a linked list over Python list and one reason Python list usually beats it.

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