링크
LRU 캐시 구현
class Node:
def __init__(self, key: int, val: int, next: 'Node' = None, prev: 'Node' = None):
self.key = key
self.val = val
self.next = next
self.prev = prev
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.table = {}
self.head = None
self.tail = None
def get(self, key: int) -> int:
if self.table.get(key):
node = self.table[key]
self.removeItem(node)
self.insertHead(node)
return node.val
else:
return -1
def put(self, key: int, value: int) -> None:
if self.table.get(key):
node = self.table[key]
self.removeItem(node)
self.insertHead(node)
node.val = value
return
node = Node(key, value)
if self.size >= self.capacity:
self.removeTail()
else:
self.size += 1
self.insertHead(node)
def removeTail(self):
if len(self.table) == 0: return
del self.table[self.tail.key]
if self.head == self.tail:
self.head = self.tail = None
else:
self.tail = self.tail.prev
self.tail.next = None
def insertHead(self, node: 'Node'):
node.next = self.head
if self.head:
self.head.prev = node
self.head = node
node.prev = None
if not self.tail:
self.tail = node
self.table[node.key] = node
def removeItem(self, node: 'Node'):
prev = node.prev
next = node.next
if prev:
prev.next = next
else:
self.head = next
if next:
next.prev = prev
else:
self.tail = prev