Sub topic 9
Combining both ideas: the circular doubly linked list
This chapter assumes you know how a singly linked list stores nodes, how the doubly linked node adds a prev pointer, and what a sentinel node is. You should also be comfortable with Python classes and generators, and with Big-O notation.
The idea
A circular doubly linked list uses three ideas together:
- Each node has
prevandnext. - The last node's
nextpoints back to the first node, and the first node'sprevpoints to the last. - One extra node, the sentinel, sits in the ring and holds no data.
With the sentinel in place, the ring is never truly empty. An empty list is a sentinel whose prev and next both point to itself. Every real node always has a non-None prev and next, so no operation has to ask whether it is at an end.
The implementation
The class below builds the ring in its constructor. All insertion goes through one helper that splices a new node between two existing neighbours.
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.nextpush_front inserts between the sentinel and its current next. push_back inserts between the sentinel's current prev and the sentinel. These are the same operation with different neighbours. When the list is empty, both neighbours are the sentinel, and the splice still works.
Why the special cases disappear
Compare remove here with the version for a plain doubly linked list. The plain version needs four branches: whether the node is the head, and whether it is the tail. Here the two lines of pointer surgery are enough, because a node's neighbours are always real objects. If the removed node was the first real node, its prev is the sentinel, and the sentinel's next is updated. The same holds at the other end.
Iteration changes too. A circular list never reaches None, so the loop stops when it returns to the sentinel. That check is why the sentinel must be a distinct object that cannot be mistaken for data.
Using 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]push_front returns the node, and remove takes that node. Removal costs O(1) because the node already knows both neighbours. No search is needed.
Common errors
- Removing the sentinel.
removedoes not guard against this. Callers should only pass nodes returned bypush_frontorpush_back. - Removing a node twice. After the first call,
prevandnextareNone, so the second call raisesAttributeError. This is useful, because it fails loudly instead of corrupting the ring. - Updating only one direction. Setting
pred.nextbut forgettingsucc.prevleaves a list that iterates correctly forward and breaks when walked backward. - Comparing with
==. Useiswhen checking for the sentinel, since a node's value could define its own equality.
Exercise
In the CircularDoublyList above, what are the values of the sentinel's prev and next after construction, and why does push_back still work on this empty list?
Show answer
Both point to the sentinel itself. pushback calls insert_between(value, sentinel.prev, sentinel), so pred and succ are both the sentinel. The new node gets prev and next set to the sentinel, and the sentinel's next and prev are set to the new node. No empty-list branch is needed.
Exercise
Write a method reversed(self) that yields the values from last to first.
Show answer
Walk backward from the sentinel's prev until you return to the sentinel: def reversed(self): node = self.sentinel.prev while node is not self.sentinel: yield node.value node = node.prev