Doubly Linked List With Sentinel Nodes
Sentinel head and tail nodes make append and unlink constant-time with no None checks, and iteration walks head.next until it reaches the tail sentinel.
Code
# Doubly linked list with sentinel head/tail: unlinking never needs
# None checks because every real node has two live neighbours
class Node:
__slots__ = ('value', 'prev', 'next')
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
head = Node(None)
tail = Node(None)
head.next = tail
tail.prev = head
self._head = head
self._tail = tail
def append(self, value):
node = Node(value)
last = self._tail.prev
last.next = node
node.prev = last
node.next = self._tail
self._tail.prev = node
return node
def unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
node.prev = node.next = None
def __iter__(self):
node = self._head.next
while node is not self._tail:
yield node.value
node = node.next
values = DoublyLinkedList()
first = values.append('alpha')
values.append('beta')
values.append('gamma')
print(list(values))
# O(1) removal by node reference — no scan needed
values.unlink(first)
print(list(values))Output
Captured from a sandboxed run of this snippet in the build pipeline.
['alpha', 'beta', 'gamma']
['beta', 'gamma']How it works
Doubly Linked List With Sentinel Nodes is built around the classes Node and DoublyLinkedList and the functions __init__, append, unlink and __iter__.
while node is not self._tail is the loop that carries the per-item work.
Caveats
- The third-party count is zero; the runtime already has every API used here.
Putting it to use
The signature you will call most reads def append(self, value)
Import append from the file and call it — the rest of the code is implementation detail.
Core lines
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
def append(self, value):
node = Node(value)
last = self._tail.prev
last.next = node
node.prev = last
node.next = self._tail
self._tail.prev = node
return node
def unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
node.prev = node.next = None
Interactive Tools for This Topic
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `__init__`, `append`, `unlink` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.