Skip to content

Doubly Linked List - A Line Linked Both Ways ​

Node = data + 2 arrows (prev: the person in front, next: the person behind). A doubly linked list is these nodes holding hands with the ones in front and behind.

None ← [A] ⇄ [B] ⇄ [C] → None
      head              tail

Why Use This for LRU? ​

When you always want "the most recently used item" at the front (near the head):

  • Insert at the front (insert_front): only the arrows of the new node, the head, and the next node change → O(1)
  • Remove a specific node (remove_node): if you already have that node, just connect the arrows of its front and back neighbors to each other → O(1)
  • Move to the front (move_to_front): remove it, then insert it at the front → O(1)

With a plain array (list), removing a middle element means shifting everything after it, so it is O(n). The key point is that a linked list only changes arrows and never shifts positions, so it is O(1).

python
class Node:
    """One cell of a doubly linked list"""
    def __init__(self, data):
        self.prev = None   # previous node
        self.next = None   # next node
        self.data = data   # actual value

Summary ​

ConceptPlain-language summary
Doubly linked listA line where everyone holds hands front and back. Reordering the line is instant (O(1))

Source: Codyssey-B1/B5-1