Doubly Linked Lists with Sentinels
In a linked list the order of the elements is not given by positions in memory but by pointers: each node stores its key and a pointer to the next node. Nothing ever has to shift, so inserting or deleting at a known place costs , whereas an array would move up to elements. The price is that position is no longer one step away: reaching it means following pointers.
In a doubly linked list every node also points to its predecessor, so a node can be removed knowing only the node itself. This lesson builds that structure with a sentinel, a dummy node that removes every special case for the ends of the list. The DSA course covers singly linked lists and their variants by example.
The operations, and the boundary cases
A node has fields , and . Without a sentinel the list has a head pointer, the first node has prev = NIL and the last has next = NIL. Every operation then needs extra branches: deleting the first node must update head, deleting the last must not touch next.prev, inserting into an empty list is different again.
The animation shows the basic operations on a list; note how finding or deleting by key walks from the front, one node at a time.
The animation draws a singly linked list, so append walks all the way to the tail. The doubly linked version below reaches the tail in one step, through the sentinel's prev pointer.
The sentinel
A sentinel is a node with no key that sits between the tail and the head: is the first node and the last, and the first node's prev and the last node's next point back to it. The list becomes a ring. An empty list is the sentinel pointing to itself.
LIST-INSERT-AFTER(L, x, p) // put node x right after node p (p may be L.nil)
1 x.next = p.next
2 x.prev = p
3 p.next.prev = x
4 p.next = x
LIST-DELETE(L, x) // x is a real node of L
1 x.prev.next = x.next
2 x.next.prev = x.prev
LIST-SEARCH(L, k)
1 x = L.nil.next
2 while x != L.nil and x.key != k
3 x = x.next
4 return x // L.nil means "not found"Not one if. Inserting at the front is LIST-INSERT-AFTER with , at the back with . Deletion and insertion are ; search is in the worst case.
Invariant: for every node of the ring, including the sentinel, and . Each procedure changes exactly the four (insert) or two (delete) pointers needed to keep it. The program checks the invariant after every operation of the animation's sequence.
class Node:
__slots__ = ("key", "prev", "next")
def __init__(self, key=None):
self.key, self.prev, self.next = key, self, self # alone, it is a ring
class DList:
def __init__(self):
self.nil = Node() # the sentinel
def insert_after(self, x, p):
x.next, x.prev = p.next, p
p.next.prev = x
p.next = x
def delete(self, x):
x.prev.next = x.next
x.next.prev = x.prev
def search(self, k):
x = self.nil.next
while x is not self.nil and x.key != k:
x = x.next
return x
def prepend(self, k): self.insert_after(Node(k), self.nil)
def append(self, k): self.insert_after(Node(k), self.nil.prev)
def keys(self, backwards=False):
out, x = [], (self.nil.prev if backwards else self.nil.next)
while x is not self.nil:
out.append(x.key)
x = x.prev if backwards else x.next
return out
def check(self):
x = self.nil
while True:
assert x.next.prev is x and x.prev.next is x
x = x.next
if x is self.nil:
return True
L = DList()
for k in [9, 16, 4]:
L.append(k)
print("start ", L.keys())
L.prepend(1); print("prepend 1 ", L.keys())
L.append(7); print("append 7 ", L.keys())
print("search 4 finds ", L.search(4).key, "| search 8 finds the sentinel:", L.search(8) is L.nil)
L.delete(L.search(16)); print("delete 16 ", L.keys())
p = L.nil.next.next # the node at position 1
L.insert_after(Node(5), p); print("insert 5 at pos 2", L.keys())
print("backwards ", L.keys(backwards=True), "| invariant holds:", L.check())start [9, 16, 4]
prepend 1 [1, 9, 16, 4]
append 7 [1, 9, 16, 4, 7]
search 4 finds 4 | search 8 finds the sentinel: True
delete 16 [1, 9, 4, 7]
insert 5 at pos 2 [1, 9, 5, 4, 7]
backwards [7, 4, 5, 9, 1] | invariant holds: True
A sentinel costs one extra node per list. When a program keeps many short lists (the chains of a hash table, for example) that overhead adds up, and the plain version with NIL pointers can be the better choice. Sentinels simplify code; they do not change the asymptotic cost of anything.
In C++
The C++ version stores the nodes in a std::vector and links them by index, with index 0 as the sentinel. That avoids manual new and delete, and the invariant check is the same loop. A fixed-seed random test applies 10,000 operations and compares with std::list.
#include <cstdio>
#include <iterator>
#include <list>
#include <random>
#include <vector>
struct DList {
struct Node { int key, prev, next; };
std::vector<Node> nodes{{0, 0, 0}}; // nodes[0] is the sentinel
int insert_after(int p, int key) {
int x = static_cast<int>(nodes.size());
nodes.push_back({key, p, nodes[p].next});
nodes[nodes[p].next].prev = x;
nodes[p].next = x;
return x;
}
void erase(int x) {
nodes[nodes[x].prev].next = nodes[x].next;
nodes[nodes[x].next].prev = nodes[x].prev;
}
bool check() const {
int x = 0;
do {
if (nodes[nodes[x].next].prev != x || nodes[nodes[x].prev].next != x) return false;
x = nodes[x].next;
} while (x != 0);
return true;
}
};
int main() {
DList L;
std::list<int> ref;
std::vector<int> live; // node ids currently in L, in list order
std::mt19937 rng(11);
for (int step = 0; step < 10000; ++step) {
if (live.empty() || rng() % 3 != 0) { // insert after a random position
std::size_t pos = rng() % (live.size() + 1); // 0 = at the front
int key = static_cast<int>(rng() % 100);
int x = L.insert_after(pos == 0 ? 0 : live[pos - 1], key);
live.insert(live.begin() + pos, x);
ref.insert(std::next(ref.begin(), pos), key);
} else { // delete a random node
std::size_t pos = rng() % live.size();
L.erase(live[pos]);
live.erase(live.begin() + pos);
ref.erase(std::next(ref.begin(), pos));
}
}
bool same = true;
auto it = ref.begin();
for (int x = L.nodes[0].next; x != 0; x = L.nodes[x].next, ++it) same = same && (*it == L.nodes[x].key);
std::printf("size %zu, matches std::list: %s, invariant: %s\n",
ref.size(), same ? "yes" : "no", L.check() ? "yes" : "no");
}size 3282, matches std::list: yes, invariant: yes
Where O(1) deletion matters: an LRU cache
A cache with a fixed capacity that evicts the least recently used key needs three things at once: find a key quickly, move a key to the "most recent" end when it is used, and remove the oldest key. A hash map from keys to list nodes plus a doubly linked list ordered by recency does all three in : the map finds the node, LIST-DELETE unlinks it without a search, and it is re-inserted after the sentinel. The oldest key is always . This is the practice problem LRU Cache.
class Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key=None, value=None):
self.key, self.value, self.prev, self.next = key, value, self, self
class LRUCache:
def __init__(self, capacity):
self.cap, self.nil, self.where = capacity, Node(), {}
def _unlink(self, x):
x.prev.next, x.next.prev = x.next, x.prev
def _push_front(self, x): # most recent right after the sentinel
x.next, x.prev = self.nil.next, self.nil
self.nil.next.prev = x
self.nil.next = x
def get(self, key):
x = self.where.get(key)
if x is None:
return -1
self._unlink(x); self._push_front(x)
return x.value
def put(self, key, value):
if key in self.where:
x = self.where[key]; x.value = value
self._unlink(x); self._push_front(x)
return
if len(self.where) == self.cap:
old = self.nil.prev # least recently used
self._unlink(old); del self.where[old.key]
print(f" evict {old.key}")
x = Node(key, value); self.where[key] = x; self._push_front(x)
def order(self):
out, x = [], self.nil.next
while x is not self.nil:
out.append(x.key); x = x.next
return out
c = LRUCache(2)
for op in ["put 1 10", "put 2 20", "get 1", "put 3 30", "get 2", "get 3", "put 1 11", "get 1"]:
name, *args = op.split()
r = getattr(c, name)(*map(int, args))
print(f"{op:9} -> {'' if r is None else r!s:3} recency {c.order()}")put 1 10 -> recency [1]
put 2 20 -> recency [2, 1]
get 1 -> 10 recency [1, 2]
evict 2
put 3 30 -> recency [3, 1]
get 2 -> -1 recency [3, 1]
get 3 -> 30 recency [3, 1]
put 1 11 -> recency [1, 3]
get 1 -> 11 recency [1, 3]
Python's collections.OrderedDict is built the same way (a dict plus a doubly linked list), and its move_to_end and popitem(last=False) give an LRU cache in a few lines.
Test yourself
What does LIST-SEARCH return in a sentinel list when the key is absent?
None- the sentinel
- the last node
- it loops forever
How many pointer fields does LIST-DELETE change?
- one
- two
- four
Why does an LRU cache use a **doubly** linked list rather than a singly linked one?
- To iterate backwards for printing
- So a node found through the hash map can be unlinked in without searching for its predecessor
- Because singly linked lists cannot hold values
- To use less memory
An empty doubly linked list with a sentinel consists of...
- no nodes and
head = NIL - the sentinel with
nextandprevboth pointing to itself - two sentinels, one at each end
- the sentinel with
next = NIL