Sub topic 7
Sentinel nodes and simpler edge cases
This chapter assumes you can write a singly linked list with Node and LinkedList classes, and that you have seen push_front, append, and delete_value. It also assumes you know introductory Big-O. You will remove the special cases for the head of the list by adding one extra node, then see where the same idea appears in other list code.
The problem: the head is special
Every node in a singly linked list is referenced by the next field of the node before it. The first node is the exception. Nothing precedes it, so the list object's head field points to it instead.
Any operation that changes the first node must therefore update a different variable than the one it updates everywhere else. Here is delete_value from the earlier chapter:
def delete_value(self, value):
if self.head is None:
return False
if self.head.value == value: # special case 1: empty list
self.head = self.head.next # special case 2: the head itself
return True
current = self.head
while current.next is not None:
if current.next.value == value:
current.next = current.next.next
return True
current = current.next
return FalseThe method has two branches before the real loop starts. append has the same problem, because an empty list needs self.head = new_node while a non-empty list needs current.next = new_node. These branches are where most bugs in linked list code occur.
The idea: a sentinel node
A sentinel node (also called a dummy node) is an extra node placed in front of the real first node. It holds no meaningful value. Its only job is to make the real first node look like any other node, because the sentinel's next now points to it.
With a sentinel in place, "the node before the target" always exists. Deleting the first real node becomes the same operation as deleting any other: set predecessor.next = predecessor.next.next. The empty list is also an ordinary case. It is a sentinel whose next is None.
Sentinel as a local variable
You don't have to change your list class to use a sentinel. A function can create one for the duration of a call, then return dummy.next as the new head. This works well for functions that take and return a head.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def from_iterable(values):
head = None
for v in reversed(list(values)):
head = Node(v, head)
return head
def to_list(head):
out = []
while head is not None:
out.append(head.value)
head = head.next
return out
def delete_value(head, value):
dummy = Node(None, head)
current = dummy
while current.next is not None:
if current.next.value == value:
current.next = current.next.next
break
current = current.next
return dummy.next
print(to_list(delete_value(from_iterable([1, 2, 3]), 1))) # [2, 3]
print(to_list(delete_value(from_iterable([1, 2, 3]), 3))) # [1, 2]
print(to_list(delete_value(from_iterable([]), 1))) # []The function has no if for the head and no if for an empty list. The loop condition current.next is not None handles both. Deleting 1 works because current starts at the dummy, so current.next is the head.
The function returns dummy.next, not head. If the original head was deleted, head still points to the removed node, and returning it would give the caller a stale list. Forgetting this is the most common sentinel bug.
Removing every match
Sentinels pay off more when an operation can change the head several times. This version removes all nodes with a given value:
def remove_all(head, value):
dummy = Node(None, head)
current = dummy
while current.next is not None:
if current.next.value == value:
current.next = current.next.next # skip it, stay put
else:
current = current.next # advance only on a keep
return dummy.next
print(to_list(remove_all(from_iterable([7, 7, 1, 7, 2, 7]), 7))) # [1, 2]After a deletion, current does not advance. The node that was two steps ahead is now current.next, and it might also match. If you advanced after every deletion, [7, 7, 1] would leave one 7 behind. Without a sentinel you would need a separate loop to strip matching nodes from the front before the main loop could begin.
Sentinel as a permanent part of the list
You can also store the sentinel inside the list object for its whole lifetime. The head field is replaced by _sentinel, and the first real node is always _sentinel.next.
class SentinelList:
def __init__(self):
self._sentinel = Node(None)
self._tail = self._sentinel # last node, or the sentinel if empty
self._size = 0
def __len__(self):
return self._size
def __iter__(self):
current = self._sentinel.next
while current is not None:
yield current.value
current = current.next
def push_front(self, value):
node = Node(value, self._sentinel.next)
self._sentinel.next = node
if self._tail is self._sentinel: # list was empty
self._tail = node
self._size += 1
def append(self, value):
node = Node(value)
self._tail.next = node # works for empty and non-empty lists
self._tail = node
self._size += 1
def delete_value(self, value):
prev = self._sentinel
while prev.next is not None:
if prev.next.value == value:
if prev.next is self._tail:
self._tail = prev # removed the last node
prev.next = prev.next.next
self._size -= 1
return True
prev = prev.next
return False
items = SentinelList()
for v in (1, 2, 3):
items.append(v)
items.push_front(0)
items.delete_value(3)
items.delete_value(0)
print(list(items), len(items)) # [1, 2] 2Because the list keeps a _tail reference, append runs in O(1) instead of walking the whole chain. The sentinel is what makes that simple. When the list is empty, _tail is the sentinel, so self._tail.next = node needs no branch.
A permanent sentinel does not remove every edge case. The tail reference is a second piece of state that has to stay correct. delete_value must move _tail back when it removes the last node, and push_front must set it when the list was empty. A sentinel removes the head branch but not the bookkeeping for the tail.
Sentinels in doubly linked lists
In a doubly linked list, the ends cause the most branches. unlink from the earlier chapter needs if node.prev is not None and if node.next is not None because a node may be at either end.
A common fix is a single sentinel that links to itself, forming a circle. In an empty list, sentinel.next and sentinel.prev both point to the sentinel. The sentinel acts as both the head's predecessor and the tail's successor, so every real node has two real neighbors.
class DNode:
def __init__(self, value):
self.value = value
self.prev = self
self.next = self
class DList:
def __init__(self):
self.sentinel = DNode(None)
def insert_before(self, node, value):
new = DNode(value)
new.prev = node.prev
new.next = node
node.prev.next = new
node.prev = new
return new
def append(self, value):
return self.insert_before(self.sentinel, value)
def unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def __iter__(self):
current = self.sentinel.next
while current is not self.sentinel:
yield current.value
current = current.next
d = DList()
a = d.append("a")
b = d.append("b")
d.append("c")
d.unlink(a)
d.unlink(b)
print(list(d)) # ['c']unlink has two lines and no if. Appending to the end is insert_before(sentinel, value), because the node before the sentinel is the tail. Iteration stops when it returns to the sentinel instead of when it reaches None. Many standard library implementations of linked lists use this design.
Trade-offs and pitfalls
| Aspect | Effect |
|---|---|
| Branches in insert and delete | Fewer, because the head is no longer special |
| Memory | One extra node per list, a fixed cost |
| Empty-list check | Test `sentinel.next is None` (or `is sentinel` when circular) instead of `head is None` |
| Traversal | Start at `sentinel.next`, never at the sentinel itself |
| Sentinel value | Never treated as data, so a search must not compare against it |
- Starting traversal at the sentinel. If your loop starts at
_sentinel, it yieldsNoneas the first item. Always begin atsentinel.next. - Returning the wrong head. With a local dummy, return
dummy.next. Never return the oldheadafter an operation that might have removed it. - Using
dummy.value. In merge or filter code, the dummy's value is never read. Comparing against it is a bug. - Counting the sentinel. A stored
_sizeshould count real nodes only. If you compute length by walking the chain, start atsentinel.next. - Circular loops. With a circular sentinel,
while current is not Nonenever ends, because no node'snextisNone. Compare with the sentinel instead.
A sentinel is a good choice when a list operation has several branches for the first or last node, or when it may change the head more than once. For a single push_front, which already needs no special case, a sentinel adds nothing.
Where you have already seen this
The merge_sorted function from the spine uses a local dummy. It builds the result by attaching nodes to tail, which starts at the dummy. The first attachment is the same operation as every later one, so the loop has no "is the result empty yet?" branch. The chapter on merging sorted lists returns to this.
Exercise
Write remove_duplicates_sorted(head) for a sorted singly linked list. It keeps the first node of each run of equal values and removes the rest. Use Node, from_iterable, and to_list from this chapter. Does this function need a sentinel? Explain.
Show answer
No sentinel is needed, because the first node is never removed. It always survives as the first of its run, so the head never changes. def removeduplicatessorted(head): current = head while current is not None and current.next is not None: if current.next.value == current.value: current.next = current.next.next else: current = current.next return head For example, tolist(removeduplicatessorted(fromiterable([1, 1, 2, 3, 3, 3]))) returns [1, 2, 3]. If the task were to remove every value that appears more than once (keeping none of them), the head could be removed, and a dummy node would be the right tool.