双向链表、循环链表和 LRU 缓存
双向链表的每个结点既有 prev 又有 next,结点能在 O(1) 内把自己摘下来;再配上一个 dict,就是 get 和 put 都是 O(1) 的 LRU 缓存。
浏览器、数据库、CDN 都有一种缓存:最多放 3 个(或 3 万个),满了就扔掉最久没用过的那个,叫 LRU(Least Recently Used)。要求 get 和 put 都是 O(1)。dict 能一步找到键,但不知道谁最久没用;用 list 排先后,每次「用过了挪到最前面」都是 O(n)。答案是把 dict 和双向链表拼起来:dict 一步找到结点,双向链表一步把它摘下来放到最前面。上一课说过,单链表只拿着结点本身删不掉它,因为找不到前一个;双向链表的结点自己记着前一个。
双向链表:多一个 prev
双向链表的结点有两个引用:prev 指着前一个,next 指着后一个。拿着结点 b,删掉它只要让前后两个互相指:b.prev.next = b.next,b.next.prev = b.prev。点「播放」看两边的箭头怎么改:
b↓1b.prev.next = b.next2b.next.prev = b.prev
真正写的时候,在两头各放一个哨兵结点(上一课哑结点的两头版):head 和 tail 不放数据,真正的结点都在它们中间。这样每个真结点都有前一个和后一个,插入、删除永远不用判断 None。
1class DNode:2 def __init__(self, key=None):3 self.key = key4 self.prev = None5 self.next = None6 7class DList:8 def __init__(self):9 self.head = DNode() # 两个哨兵:真结点都在它们中间10 self.tail = DNode()11 self.head.next = self.tail12 self.tail.prev = self.head13 14 def push_front(self, node):15 node.prev = self.head # 先改新结点自己的两个16 node.next = self.head.next17 self.head.next.prev = node # 再改邻居:先改后面那个的 prev18 self.head.next = node19 20 def remove(self, node):21 node.prev.next = node.next22 node.next.prev = node.prev23 24 def forward(self):25 out, cur = [], self.head.next26 while cur is not self.tail:27 out.append(cur.key)28 cur = cur.next29 return out30 31 def backward(self):32 out, cur = [], self.tail.prev33 while cur is not self.head:34 out.append(cur.key)35 cur = cur.prev36 return out37 38L = DList()39nodes = {}40for k in "abcd":41 nodes[k] = DNode(k)42 L.push_front(nodes[k])43print(L.forward(), L.backward())44L.remove(nodes["b"]) # 拿着结点就能删:O(1)45print(L.forward())46L.remove(nodes["a"])47L.push_front(nodes["a"]) # 挪到最前面:先摘下,再放回去48print(L.forward())
['d', 'c', 'b', 'a'] ['a', 'b', 'c', 'd'] ['d', 'c', 'a'] ['a', 'd', 'c']
push_front 的四行,顺序也有讲究:如果先写 self.head.next = node,下一行的 self.head.next.prev 就成了 node.prev,原来第一个结点的 prev 没改到。和单链表一样:先接好新结点,最后再改指着旧结点的那个引用。
双向链表里拿着结点 b,找它的前一个要多久?
b.prev 一步就到,O(1)。单链表没有 prev,才要从头再走一遍,O(n):所以单链表只拿着结点本身删不掉它。拿着 b 把它删掉以后,打印什么?
1class DNode:2 def __init__(self, val=None):3 self.val = val4 self.prev = None5 self.next = None6 7a, b, c = DNode(1), DNode(2), DNode(3)8a.next, b.prev, b.next, c.prev = b, a, c, b9b.prev.next = b.next10b.next.prev = b.prev11print(a.next.val, c.prev.val)
b.prev.next = b.next 让 a 往后直接指 c;b.next.prev = b.prev 让 c 往回直接指 a。两个方向都跳过了 b:打印 3 1。只改一个方向,往回走时还会走到已经删掉的 b。把 push_front 的四行排好,让正着走和倒着走都对:打印 [3, 2, 1] [1, 2, 3]。
node.prev = self.headself.head.next.prev = nodenode.next = self.head.nextself.head.next = node
[3, 2, 1] [1, 2, 3]
self.head.next 还是原来的第一个),再改原来第一个的 prev,最后才改 self.head.next。self.head.next = node 一旦提前,后面的 self.head.next 就都成了 node 自己,原来的第一个找不到了。循环链表:尾巴接回头
把最后一个结点的 next 指回第一个,就是循环链表:没有 None,从哪个结点出发都能绕一圈回来。经典用法是约瑟夫问题:n 个人围一圈,从 1 开始数,数到 k 的出局,从下一个人重新数,谁留到最后?
prev↓1prev = tail2while prev.next is not prev:3 for _ in range(k - 1):4 prev = prev.next5 out.append(prev.next.val)6 prev.next = prev.next.next7print(out, prev.val)
遍历循环链表不能等 None(永远等不到),要等「又回到出发的那个」:
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def make_circle(n):7 head = Node(1)8 tail = head9 for v in range(2, n + 1):10 tail.next = Node(v)11 tail = tail.next12 tail.next = head # 首尾相连13 return head, tail14 15def show(head):16 out, cur = [], head17 while True:18 out.append(cur.val)19 cur = cur.next20 if cur is head: # 回到出发的那个21 break22 return out23 24def josephus(n, k):25 head, tail = make_circle(n)26 out = []27 prev = tail28 while prev.next is not prev:29 for _ in range(k - 1):30 prev = prev.next31 out.append(prev.next.val)32 prev.next = prev.next.next33 return out, prev.val34 35print(show(make_circle(5)[0]))36print(josephus(5, 3))37print(josephus(7, 3))
[1, 2, 3, 4, 5] ([3, 1, 5, 2], 4) ([3, 6, 2, 7, 5, 1], 4)
| 单链表 | 双向链表 | 循环链表 | |
|---|---|---|---|
| 每个结点 | val、next | val、prev、next | 同单链表,尾巴指回头 |
| 拿着结点 x,删掉它 | O(n):先找前一个 | O(1):x.prev 就是 | O(n):绕一圈找前一个 |
| 能不能往回走 | 不能 | 能 | 不能,但能绕回来 |
| 遍历到哪停 | cur is None | cur is tail(哨兵) | cur is head(回到起点) |
循环链表 3 → 7 → 9 → 回到 3。这样数结点,打印几?
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6c = Node(9)7b = Node(7, c)8a = Node(3, b)9c.next = a10head = a11cur = head12n = 013while cur is not head:14 n += 115 cur = cur.next16print(n)
while 先判断,cur is not head 一上来就不成立,循环一轮都不进:打印 0。Python 没有 do … while,绕一圈要么用 while True 先走一步再判断「回到 head 了吗」,要么从 head.next 开始、计数从 1 开始。一个循环单链表只记着最后一个结点 tail。第一个结点是哪个?
tail.next。只记 tail,头和尾都能一步拿到:这就是只存尾的好处,在头上加、在尾上加都是 O(1)。6 个人围一圈,从 1 开始数,数到 2 的出局,从下一个人重新数。最后留下的是几号?
一圈有几个
✓补全 count_circle(head):数循环链表有几个结点。不能等 None,要等回到 head;空链表(head 是 None)返回 0。
5 1 0
1class Node:2 def __init__(self, val, next=None):3 self.val = val4 self.next = next5 6def count_circle(head):7 # 从 head 出发,走到又回到 head 为止8 return 09 10a = Node(1, Node(2, Node(3, Node(4, Node(5)))))11a.next.next.next.next.next = a12b = Node(9)13b.next = b14print(count_circle(a), count_circle(b), count_circle(None))
LRU 缓存:dict + 双向链表
两样东西各管一件事:
- dict:键 → 结点,一步找到。
- 双向链表:从最近用过排到最久没用。
get或put用到一个键,就把它的结点摘下来放到最前面;满了就删掉最后一个(tail.prev)。
结点里要存 key:删链表最后一个时,要靠它的 key 去 dict 里删掉对应的键。
1class DNode:2 def __init__(self, key=None, val=None):3 self.key = key4 self.val = val5 self.prev = None6 self.next = None7 8class LRUCache:9 def __init__(self, capacity):10 self.capacity = capacity11 self.map = {} # key -> 结点12 self.head = DNode() # 最前面:最近用过13 self.tail = DNode() # 最后面:最久没用14 self.head.next = self.tail15 self.tail.prev = self.head16 17 def _remove(self, node):18 node.prev.next = node.next19 node.next.prev = node.prev20 21 def _push_front(self, node):22 node.prev = self.head23 node.next = self.head.next24 self.head.next.prev = node25 self.head.next = node26 27 def get(self, key):28 if key not in self.map:29 return -130 node = self.map[key]31 self._remove(node) # 用过了:挪到最前面32 self._push_front(node)33 return node.val34 35 def put(self, key, val):36 if key in self.map:37 self._remove(self.map[key])38 elif len(self.map) == self.capacity:39 old = self.tail.prev # 最久没用的40 self._remove(old)41 del self.map[old.key]42 node = DNode(key, val)43 self.map[key] = node44 self._push_front(node)45 46c = LRUCache(2)47c.put(1, 1)48c.put(2, 2)49out = [c.get(1)]50c.put(3, 3) # 满了:2 最久没用,删掉51out.append(c.get(2))52c.put(4, 4) # 满了:1 最久没用,删掉53out += [c.get(1), c.get(3), c.get(4)]54print(out)
[1, -1, -1, 3, 4]
面试里: LRU 缓存(力扣 146)几乎必考,面试官常说「不要用 OrderedDict」,就是要你写出上面这样的 dict + 双向链表,两头带哨兵。答复杂度:get、put 都是 O(1),空间 O(capacity)。约瑟夫问题(力扣 1823)可以用循环链表模拟,O(nk)。
LRU 缓存的链表结点里,为什么除了 val 还要存 key?
tail.prev。dict 是「key → 结点」,不知道 key 就没法 del self.map[...],dict 里会留下一个已经不在链表里的结点。找结点靠 dict,链表从来不按 key 找。容量 3 的 LRU,依次用到 1 2 3 1 4。放 4 时被淘汰的是哪个?
写出 LRU 的 get 和 put
✓_remove 和 _push_front 已经写好了。补全 get 和 put:用到的键挪到最前面;放新键时满了,先删掉 tail.prev(记得也从 dict 里删掉)。
A ['a', 'c', 'b'] -1 ['d', 'a', 'c'] C2 ['c', 'd', 'a']
1class DNode:2 def __init__(self, key=None, val=None):3 self.key = key4 self.val = val5 self.prev = None6 self.next = None7 8class LRUCache:9 def __init__(self, capacity):10 self.capacity = capacity11 self.map = {}12 self.head = DNode()13 self.tail = DNode()14 self.head.next = self.tail15 self.tail.prev = self.head16 17 def _remove(self, node):18 node.prev.next = node.next19 node.next.prev = node.prev20 21 def _push_front(self, node):22 node.prev = self.head23 node.next = self.head.next24 self.head.next.prev = node25 self.head.next = node26 27 def get(self, key):28 # 不在:-1;在:挪到最前面,返回 val29 return -130 31 def put(self, key, val):32 # 已经有:先摘掉旧结点;满了:删 tail.prev;再放新结点到最前面33 pass34 35 def keys(self):36 out, cur = [], self.head.next37 while cur is not self.tail:38 out.append(cur.key)39 cur = cur.next40 return out41 42c = LRUCache(3)43for k in "abc":44 c.put(k, k.upper())45print(c.get("a"), c.keys())46c.put("d", "D")47print(c.get("b"), c.keys())48c.put("c", "C2")49print(c.get("c"), c.keys())
工作里这样写
工作里不用自己拼。collections.OrderedDict 在 CPython 里就是一个 dict 加一条双向链表,move_to_end(key) 把一个键挪到最后、popitem(last=False) 删掉最前面的,都是 O(1)。LRU 十几行:
1from collections import OrderedDict2 3class LRUCache:4 def __init__(self, capacity):5 self.capacity = capacity6 self.data = OrderedDict()7 8 def get(self, key):9 if key not in self.data:10 return -111 self.data.move_to_end(key) # 用过:挪到最后(最新的一头)12 return self.data[key]13 14 def put(self, key, val):15 self.data[key] = val16 self.data.move_to_end(key)17 if len(self.data) > self.capacity:18 self.data.popitem(last=False) # 删最前面(最久没用)19 20c = LRUCache(2)21c.put(1, 1)22c.put(2, 2)23out = [c.get(1)]24c.put(3, 3)25out.append(c.get(2))26c.put(4, 4)27out += [c.get(1), c.get(3), c.get(4)]28print(out)29print(list(c.data))
[1, -1, -1, 3, 4] [3, 4]
注意方向和「LRU 缓存」那一关手写的相反:OrderedDict 里最后面是最新的,最前面是最久没用的。
一个最多放 3 个的 LRU,依次用到 a b c a d b,最后打印什么?
1from collections import OrderedDict2 3cache = OrderedDict()4for key in ["a", "b", "c", "a", "d", "b"]:5 if key in cache:6 cache.move_to_end(key)7 else:8 cache[key] = True9 if len(cache) > 3:10 cache.popitem(last=False)11print(list(cache))
[a, b, c];再用 a,挪到最后:[b, c, a];放 d 超了,删最前面的 b:[c, a, d];再放 b 又超了,删 c:[a, d, b]。b 被删过一次,回来时是新放进去的。要缓存的是函数的结果(同样的参数算过就不再算),直接用 functools.lru_cache:
1from functools import lru_cache2 3calls = 04 5@lru_cache(maxsize=2)6def slow_square(x):7 global calls8 calls += 19 return x * x10 11for x in [1, 2, 1, 3, 1, 2]:12 slow_square(x)13print("真正算了", calls, "次")14print(slow_square.cache_info())
真正算了 4 次 CacheInfo(hits=2, misses=4, maxsize=2, currsize=2)
OrderedDict:要自己控制「什么时候算用过」「删谁」时用;比普通 dict 多占一条链表的内存。@lru_cache(maxsize=128):给函数加缓存。参数必须可哈希(list 不行,tuple 可以);maxsize=None不限大小(就是functools.cache),记得它会一直占着内存。- 普通 dict 从 3.7 起也记得插入顺序,但没有
move_to_end;要挪只能先pop再放回去。
@lru_cache 加在 def f(nums) 上,调用时参数能不能是 list?
TypeError: unhashable type。把 list 换成 tuple(f(tuple(nums)))就可以了。小结
双向链表能 O(1) 摘掉自己;LRU = dict + 双向链表
- 双向结点多一个 prev:拿着结点就能 O(1) 删掉它
- 两头放哨兵,不用判 None;插入先接好新结点,最后改旧的引用
- 循环链表尾巴指回头:遍历要等回到出发的那个
- LRU:dict 找结点,链表排新旧;用过挪到最前,满了删最后
- 现成的:OrderedDict 的 move_to_end、popitem(last=False),@lru_cache
1node.prev.next = node.next # 摘掉 node2node.next.prev = node.prev3d.move_to_end(key) # OrderedDict:挪到最新4d.popitem(last=False) # 删最久没用的5@lru_cache(maxsize=128)