LRU缓存机制

class LRUCache {
public:
    struct Node{
        int key;
        Node *pre, *next;
        Node(int x):key(x),pre(NULL),next(NULL){}
    };
    int tot, c;
    Node *head, *tail;
    unordered_map<int, pair<int, Node*>>dic;
    LRUCache(int capacity) {
        tot=0;
        c=capacity;
        auto l1=new Node(-1);
        auto l2=new Node(-1);
        head=l1,tail=l2;
        head->next=tail;
        tail->pre=head;
    }
    
    int get(int key) {
        if(dic.find(key)==dic.end())return -1;
        Node *node=dic[key].second;
        node->pre->next=node->next;
        node->next->pre=node->pre;
        
        node->next=tail;
        node->pre=tail->pre;
        tail->pre->next=node;
        
        tail->pre=node;
        return dic[key].first;
    }
    
    void put(int key, int value) {
        if(dic.find(key)!=dic.end()){
            dic[key].first=value;
            Node *node=dic[key].second;
            node->pre->next=node->next;
            node->next->pre=node->pre;
        
            node->next=tail;
            node->pre=tail->pre;
            tail->pre->next=node;

            tail->pre=node;
        }else{
            if(tot==c){
                Node *node=head->next;
                dic.erase(node->key);
                head->next=node->next;
                node->next->pre=head;
                delete node;
                tot--;
            }
            Node *node=new Node(key);
            dic[key]=make_pair(value, node);
            
            node->next=tail;
            tail->pre->next=node;
            node->pre=tail->pre;
            tail->pre=node;
            tot++;
        }
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */

 

posted @ 2019-07-29 19:31  YF-1994  阅读(628)  评论(0编辑  收藏  举报