Skip to content

Instantly share code, notes, and snippets.

@whiledoing
Created June 9, 2018 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whiledoing/2f53753f1b53bb1f0f0390da23b7daa5 to your computer and use it in GitHub Desktop.
Save whiledoing/2f53753f1b53bb1f0f0390da23b7daa5 to your computer and use it in GitHub Desktop.
[python-LRUCache] LRU implementation #python #datastructure
class LinkedNode:
def __init__(self, value, next):
self.value = value
self.next = next
class LRUCache:
def __init__(self, capacity):
self.head = LinkedNode(None, None)
self.tail = None
self.node_pre_map = {}
self.capacity = capacity
def get(self, key):
if key not in self.node_pre_map: return -1
# remove node
pre = self.node_pre_map.pop(key)
pre.next, cur = pre.next.next, pre.next
if not cur.next: self.tail = pre
# insert node to front
self._insert_impl(cur)
return cur.value[1]
def put(self, key, value):
if key in self.node_pre_map: return
if len(self.node_pre_map) == self.capacity:
if not self.tail: return
self.tail = self.node_pre_map.pop(self.tail.value[0])
self.tail.next = None
self._insert_impl(LinkedNode((key, value), None))
def _insert_impl(self, new_node):
new_node.next = self.head.next
self.head.next = new_node
self.node_pre_map[new_node.value[0]] = self.head
if new_node.next:
self.node_pre_map[new_node.next.value[0]] = new_node
else:
self.tail = new_node
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment