用Python实现LRU Cache(链表+哈希表)

class Node:
    def __init__(self, key, val):
        self.before = None
        self.after = None
        self.key = key
        self.val = val

class LRUCache:

    def __init__(self, capacity: int):
        self.k = capacity
        self.cache = {}
        self.head = None
        self.tail = None

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        node = self.cache[key]
        if self.tail == node and self.tail.before is not None:
            self.tail = self.tail.before
        if self.head is not node:
            pre = node.before
            nex = node.after
            if pre:
                pre.after = node.after
            if nex:
                nex.before = node.before
            self.head.before = node
            node.after = self.head
            node.before = None
            self.head = node
        return node.val


    def put(self, key: int, value: int) -> None:
        n = Node(key, value)
        if key in self.cache:
            self.cache[key].val = value
            self.get(key)
        else:
            if len(self.cache) == self.k:
                self.cache.pop(self.tail.key)
                self.tail = self.tail.before
                if self.tail:
                    self.tail.after = None
            if self.tail is None:
                self.tail = n

            n.after = self.head
            if self.head:
                self.head.before = n
            self.head = n
            self.cache[n.key] = n




你可能感兴趣的:(用Python实现LRU Cache(链表+哈希表))