# jonas 2022.1.6
class Doublelist:
def __init__(self, key=None, val=None, pre=None, _next=None):
# key value pair
self.key = key
self.val = val
# pointer to the pre,next node
self.pre = pre
self.next = _next
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.hashMap = {}
self.head = Doublelist()
self.end = Doublelist()
self.head.next = self.end
self.end.pre = self.head
def len(self):
return len(self.hashMap)
def get(self, key: int) -> int:
# return -1 or value of the key
if key in self.hashMap:
# adjust the key to the head of the list
node = self.hashMap[key][1]
node.pre.next = node.next
node.next.pre = node.pre
node.pre = self.head
node.next = self.head.next
node.next.pre = node
node.pre.next = node
return self.hashMap[key][0]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.hashMap:
# update
self.hashMap[key][0] = value
# adjust the corresponding node to the head of the list
node = self.hashMap[key][1]
node.pre.next = node.next
node.next.pre = node.pre
node.pre = self.head
node.next = self.head.next
self.head.next.pre = node
self.head.next = node
return
if key not in self.hashMap and self.len() < self.cap:
# creat a new node for the key-value pair
node = Doublelist(key, value, self.head, self.head.next)
# add key-val pair and the corresponding node
self.hashMap[key] = [value, node]
# link the key-value pair to the head of the list
self.head.next.pre = node
self.head.next = node
return
if key not in self.hashMap and self.len() == self.cap:
# remove the last node of the list and corresponding key-value pair
node = self.end.pre
del self.hashMap[node.key]
node.pre.next = node.next
node.next.pre = node.pre
# creat a new node for key-value pair
node = Doublelist(key, value, self.head, self.head.next)
# add key-val pair and the corresponding node
self.hashMap[key] = [value, node]
self.head.next.pre = node
self.head.next = node
return
03-03
736

05-14
608

05-14
441
