Sub topic 7
Sentinel nodes and simpler edge cases
This chapter assumes you can write a singly linked list with Node and LinkedList classes, traverse it, and delete a value by fixing next references. It also assumes you know introductory Big-O. If delete_value from the previous chapter felt full of special cases, this chapter shows how to remove most of them.
The problem: the head is special
Look at delete_value again. It has three separate branches:
- The list is empty.
- The target is the head, so
self.headmust change. - The target is further along, so the previous node's
nextmust change.
Cases 2 and 3 do the same job: make the reference that points at the target skip over it. The only difference is that for the head, that reference lives in self.head, and for every other node it lives in prev.next. The head needs its own branch only because it has no node before it.
append has the same flaw. It checks whether the list is empty and assigns self.head directly, because there is no previous node to attach to.
The idea: add a node before the head
A sentinel node (also called a dummy node) is a node that holds no real data and sits permanently in front of the first real node. The list's head reference always points at the sentinel. The real first element is sentinel.next.
Now every real node has a predecessor, including the first one. The reference you edit is always some node's next, so one code path handles every position.
Rewriting the list with a sentinel
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self._sentinel = Node(None)
def push_front(self, value):
self._sentinel.next = Node(value, self._sentinel.next)
def append(self, value):
current = self._sentinel
while current.next is not None:
current = current.next
current.next = Node(value)
def delete_value(self, value):
prev = self._sentinel
while prev.next is not None:
if prev.next.value == value:
prev.next = prev.next.next
return True
prev = prev.next
return False
def __iter__(self):
current = self._sentinel.next
while current is not None:
yield current.value
current = current.next
items = LinkedList()
for v in (3, 2, 1):
items.push_front(v)
items.append(4)
print(list(items)) # [1, 2, 3, 4]
items.delete_value(1)
print(list(items)) # [2, 3, 4]
items.delete_value(99)
print(list(items)) # [2, 3, 4]Compare this with the earlier versions:
appendno longer checks for an empty list. On an empty list,current.nextis alreadyNone, so the loop ends at once and the new node attaches to the sentinel.delete_valuehas one loop and no head branch. Deleting the first real node is justsentinel.next = sentinel.next.next.- Traversal starts at
self._sentinel.next, so the sentinel never appears in the output.
Costs are unchanged: append is still O(n), and the sentinel adds one node of memory.
Sentinels in merging
The same trick appears in merge_sorted. A temporary dummy node gives tail something to attach the first chosen node to, so the loop needs no "is the result empty yet?" check. The function returns dummy.next and discards the dummy. In that case the sentinel is local to one function, not a permanent part of the list.
Trade-offs
| Aspect | Without sentinel | With sentinel |
|---|---|---|
| Head handling | Separate branch in each operation | None |
| Empty list | Explicit check | Falls out of the loop |
| Memory | None extra | One extra node |
| Risk | Forgetting to update `head` | Exposing the sentinel to callers |
A common error is returning or counting the sentinel by starting traversal at _sentinel instead of _sentinel.next. Another is writing prev = self._sentinel.next in delete_value, which brings the head special case back.
Exercise
Using the sentinel-based LinkedList above, write an insert_after_value(target, value) method that inserts value after the first node holding target, and returns False if target is not found. Does it need a special case for the head?
Show answer
No special case is needed, because the sentinel is never the target and every real node is reachable from it. def insertaftervalue(self, target, value): current = self._sentinel.next while current is not None: if current.value == target: current.next = Node(value, current.next) return True current = current.next return False