RLU算法

# -*- coding:utf8 -*-


class Node(object):

    __slots__ = ["key", "value", "prev", "next"]

    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class RLUCache(object):

    def __init__(self, capacity=0):

        self.dic = {}
        self.capacity = capacity
        self.head = Node(-1, -1)
        self.tail = Node(-1, -1)

        self.head.next = self.tail
        self.tail.prev = self.head


    def  get(self, key, default=None):
        if key in self.dic:
            node = self.dic[key]
            self.remove(node)
            self.append_to_tail(node)
            return node.value

        return  default

    def set(self, key, value):
        if key in self.dic:
            node = self.dic[key]
            self.remove(node)

        node = Node(key, value)

        self.dic[key] = node

        self.append_to_tail(node)

        if len(self.dic) > self.capacity:
            self.remove(self.head.next)
            del self.dic[key]

    def remove(self, node):
        prev_node = node.prev
        next_node = node.next

        prev_node.next = next_node
        next_node.prev = prev_node


    def append_to_tail(self, node):
        t = self.tail.prev
        t.next = node
        self.tail.prev = node
        node.prev = t
        node.next = self.tail

if __name__ == "__main__":
    dic = RLUCache(3)
    dic.set('a', 1)
    dic.set('b', 2)
    dic.set('c', 3)
    dic.set('d', 4)

    print dic.get('a')

results matching ""

    No results matching ""