mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-17 07:26:27 +00:00
fix(work): correct node insertion and eviction order in LRUCache
This commit is contained in:
@@ -87,10 +87,11 @@ class LRUCache:
|
|||||||
next_node.prev = prev_node
|
next_node.prev = prev_node
|
||||||
|
|
||||||
def _add_node(self, node):
|
def _add_node(self, node):
|
||||||
node.prev = self.head
|
# Insert just before the tail (most recent at end)
|
||||||
node.next = self.head.next
|
node.next = self.tail
|
||||||
self.head.next.prev = node # pyright: ignore[reportAttributeAccessIssue]
|
node.prev = self.tail.prev
|
||||||
self.head.next = node
|
self.tail.prev.next = node # pyright: ignore[reportAttributeAccessIssue]
|
||||||
|
self.tail.prev = node
|
||||||
|
|
||||||
def get(self, key: int) -> int:
|
def get(self, key: int) -> int:
|
||||||
if key not in self.cache:
|
if key not in self.cache:
|
||||||
@@ -113,7 +114,7 @@ class LRUCache:
|
|||||||
self._add_node(new_node)
|
self._add_node(new_node)
|
||||||
|
|
||||||
if len(self.cache) > self.capacity:
|
if len(self.cache) > self.capacity:
|
||||||
lru = self.tail.prev
|
lru = self.head.next # Oldest node is next to the head
|
||||||
self._remove_node(lru)
|
self._remove_node(lru)
|
||||||
del self.cache[lru.key] # pyright: ignore[reportAttributeAccessIssue]
|
del self.cache[lru.key] # pyright: ignore[reportAttributeAccessIssue]
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user