@@ -219,6 +219,73 @@ if (cap == cache.size()) {
219
219
220
220
![ labuladong] ( ../pictures/labuladong.png )
221
221
222
+ ![ eric wang] ( https://www.github.com/eric496 ) 提供 Python3 代码
223
+
224
+ ``` python
225
+ class ListNode :
226
+ def __init__ (self , key : int , val : int ):
227
+ self .key = key
228
+ self .val = val
229
+ self .prev = None
230
+ self .next = None
231
+
232
+
233
+ class LRUCache :
234
+ def __init__ (self , capacity : int ):
235
+ # 最大容量
236
+ self .cap = capacity
237
+ self .cache = {}
238
+ # 哨兵节点
239
+ self .sentinel = ListNode(None , None )
240
+ # 尾节点: 用于链表容量超过最大容量是快速定位、删除尾节点
241
+ self .tail = ListNode(None , None )
242
+ # 初始化双向链表
243
+ self .sentinel.next = self .tail
244
+ self .tail.prev = self .sentinel
245
+
246
+ def get (self , key : int ) -> int :
247
+ if key in self .cache:
248
+ node = self .cache[key]
249
+ # 从链表中删除该节点
250
+ self .remove_node_from_list(node)
251
+ # 把该节点添加到链表头部
252
+ self .push_node_to_front(node)
253
+ return node.val
254
+ else :
255
+ return - 1
256
+
257
+ def put (self , key : int , value : int ) -> None :
258
+ # 如果该节点已经存在那么删除该节点
259
+ if key in self .cache:
260
+ self .remove_node_from_list(self .cache[key])
261
+
262
+ # 把该节点添加到链表头部
263
+ node = ListNode(key, value)
264
+ self .cache[key] = node
265
+ self .push_node_to_front(node)
266
+
267
+ # 如果链表超过最大容量,删除链表尾部节点
268
+ if len (self .cache) > self .cap:
269
+ last_node = self .tail.prev
270
+ self .remove_node_from_list(last_node)
271
+ self .cache.pop(last_node.key)
272
+
273
+ # 从链表中删除节点
274
+ def remove_node_from_list (self , node : " ListNode" ) -> None :
275
+ prev = node.prev
276
+ nxt = node.next
277
+ prev.next = nxt
278
+ nxt.prev = prev
279
+
280
+ # 添加节点到链表头部
281
+ def push_node_to_front (self , node : " ListNode" ) -> None :
282
+ nxt = self .sentinel.next
283
+ self .sentinel.next = node
284
+ node.next = nxt
285
+ node.prev = self .sentinel
286
+ nxt.prev = node
287
+ ```
288
+
222
289
[ 上一篇:二叉堆详解实现优先级队列] ( ../数据结构系列/二叉堆详解实现优先级队列.md )
223
290
224
291
[ 下一篇:二叉搜索树操作集锦] ( ../数据结构系列/二叉搜索树操作集锦.md )
0 commit comments