Sub topic 8
Sentinel nodes and fewer special cases
This chapter assumes you can read the doubly linked list code from the earlier chapters: Node with prev and next, a list with head and tail, and None as the end marker. It also assumes you know Big-O notation.
The problem: branches at the ends
In the plain doubly linked list, almost every operation checks whether a neighbor exists. Here is remove from the earlier chapter:
def remove(self, node):
if node.prev is not None:
node.prev.next = node.next
else:
self.head = node.next
if node.next is not None:
node.next.prev = node.prev
else:
self.tail = node.prev
node.prev = None
node.next = None
self.size -= 1There are four paths: middle node, first node, last node, and only node. Each path updates a different set of references. Most bugs in list code come from forgetting one of them, usually the empty-list or one-element case.
What a sentinel is
A sentinel (also called a dummy node) is a node that holds no real value. It always exists, even when the list is empty. It takes the place of None at the ends of the list.
If you link the sentinel into a circle with the real nodes, then every real node always has a non-None prev and next. The first real node's prev is the sentinel. The last real node's next is the sentinel. An empty list is a sentinel pointing to itself.
The implementation
class _Node:
def __init__(self, value=None):
self.value = value
self.prev = None
self.next = None
class CircularDoublyList:
def __init__(self):
self._sentinel = _Node()
self._sentinel.prev = self._sentinel
self._sentinel.next = self._sentinel
self.size = 0
def _insert_between(self, value, pred, succ):
node = _Node(value)
node.prev = pred
node.next = succ
pred.next = node
succ.prev = node
self.size += 1
return node
def push_front(self, value):
return self._insert_between(value, self._sentinel, self._sentinel.next)
def push_back(self, value):
return self._insert_between(value, self._sentinel.prev, self._sentinel)
def remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
node.prev = None
node.next = None
self.size -= 1
def __iter__(self):
node = self._sentinel.next
while node is not self._sentinel:
yield node.value
node = node.nextCompare this with the earlier version.
_insert_betweenhas noif. It works for an empty list becausepredandsuccare both the sentinel. It works at the ends for the same reason: a neighbor always exists.push_frontandpush_backdiffer only in which two nodes they pass in.removeis two assignments. It works for the first, last, and only node without any extra code.- There are no
headortailattributes to keep in sync. The sentinel'snextis the head and itsprevis the tail.
Traversal changes in one place. The loop stops when it returns to the sentinel, not when it finds None. Use an identity test (is not) so a stored value can never be mistaken for the sentinel.
Trying it
lst = CircularDoublyList()
for v in (1, 2, 3):
lst.push_back(v)
node = lst.push_front(0)
lst.remove(node)
print(list(lst)) # [1, 2, 3]Costs and cautions
A sentinel costs one extra node per list, which is constant memory. Every operation keeps the same Big-O cost as before. You trade a small amount of memory for simpler code.
Summary of the trade
| Aspect | Head/tail with `None` | Circular with sentinel |
|---|---|---|
| Empty-list branch | Needed in each insert | None |
| End-of-list branch | Needed in remove and insert | None |
| Extra memory | None | One node |
| End of traversal | `node is None` | `node is sentinel` |
Exercise
In the sentinel version, what do sentinel.prev and sentinel.next point to when the list is empty, and why does push_back(5) still work without any special case?
Show answer
Both point to the sentinel itself. push_back calls _insert_between(5, sentinel.prev, sentinel), so pred and succ are both the sentinel. The new node gets prev and next set to the sentinel, then pred.next and succ.prev both become the new node. The sentinel now points to the new node on both sides, and the list is a ring of two nodes.
Exercise
Write a method pop_back(self) for CircularDoublyList that removes and returns the last value, or raises IndexError if the list is empty.
Show answer
def popback(self): if self.size == 0: raise IndexError("pop from empty list") node = self.sentinel.prev value = node.value self.remove(node) return value