Sub topic 8
Writing add_front, remove, and pop_back
This chapter assumes you know Python classes and object references, and you have read the previous chapter on sentinel nodes. You will write the three list operations that the LRU cache uses, plus move_to_front, which combines two of them.
The node and the list
Each Node holds a key, a value, and links to its neighbors. Storing the key on the node matters later. When the cache evicts a node, it needs the key to delete the matching dictionary entry.
The list keeps the most recent node right after head and the least recent node right before tail.
class Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.prev = None
self.next = None
class DoublyLinkedList:
"""Most recent node sits right after head; least recent right before tail."""
def __init__(self):
self.head = Node() # sentinel
self.tail = Node() # sentinel
self.head.next = self.tail
self.tail.prev = self.head
def add_front(self, node):
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def move_to_front(self, node):
self.remove(node)
self.add_front(node)
def pop_back(self):
if self.tail.prev is self.head:
return None
node = self.tail.prev
self.remove(node)
return nodeadd_front
Inserting a node between head and the current first node takes four pointer updates. The order matters. The first two lines point the new node at its future neighbors. The last two lines point those neighbors at the new node. If you changed head.next first, you would lose the only reference to the old first node.
Because head and tail always exist, self.head.next is never None. An empty list and a long list take the same code path.
remove
remove skips over a node by linking its two neighbors to each other. It needs only the node itself, not a search, which is why the list's cost stays constant. It does not clear the removed node's own prev and next. That is safe here, because add_front overwrites both fields whenever the node returns to the list.
move_to_front is just remove followed by add_front.
pop_back
pop_back removes the least recently used node and returns it. The check self.tail.prev is self.head detects an empty list, because only the two sentinels remain. In that case it returns None. The caller receives the real node, so it can read node.key and delete the dictionary entry.
Try it
This demo continues from the classes above.
def keys(lst):
result = []
node = lst.head.next
while node is not lst.tail:
result.append(node.key)
node = node.next
return result
dll = DoublyLinkedList()
a, b, c = Node("a", 1), Node("b", 2), Node("c", 3)
for n in (a, b, c):
dll.add_front(n)
print(keys(dll)) # ['c', 'b', 'a']
dll.move_to_front(a)
print(keys(dll)) # ['a', 'c', 'b']
dll.remove(c)
print(keys(dll)) # ['a', 'b']
print(dll.pop_back().key) # b
print(dll.pop_back().key) # a
print(dll.pop_back()) # NoneExercise
In add_front, what goes wrong if you run self.head.next = node before node.next = self.head.next?
Show answer
The new node's next would point to itself, because head.next already refers to the new node. The old first node would become unreachable from head, and the list would be broken.