python利用双向链表和map实现LRU算法
双向链表在之前:
https://blog.csdn.net/weixin_41978134/article/details/106143560
"""
@File : LRU.py
@Author: wangjiahui
@Date : 2020/5/17 14:15
@Desc : LRU缓存置换算法(最近最少使用算法)
"""
from Computer_Organization.node1 import DoubleLinkedList, Node
class LRUCache(object):
def __init__(self, capacity):
self.capacity = capacity
self.map = {}
self.list = DoubleLinkedList(self.capacity)
# 只要获取了,就把这个节点提到list链表头
def get(self, key):
if key in self.map:
node = self.map[key]
self.list.remove(node)
self.list.append_front(node)
return node.value
else:
return -1
# 如果在map里,把list里的那个节点提到链表头部,map更新映射
# 如果不在map里,分两种,一种是超size后把表尾节点删掉,
# 如果不在map里,另一种是不超size,相当于添加,把节点放到list表头就行
def put(self, key, value):
if key in self.map:
node = self.map.get(key)
self.list.remove(node)
node.value = value
self.list.append_front(node)
else:
node = Node(key, value)
# 链表缓存已经满了
if self.list.size >= self.list.capacity:
old_node = self.list.remove()
self.map.pop(old_node.key)
self.list.append_front(node)
self.map[key] = node
def print(self):
self.list.print()
if __name__ == '__main__':
cache = LRUCache(2)
cache.put(2, 2)
cache.print()
cache.put(1, 1)
cache.print()
cache.put(3, 3)
cache.print()
print(cache.get(1))
cache.print()
print(cache.get(2))
cache.print()
print(cache.get(3))
cache.print()