c++实现LRUCache

  • LRUCache实现本方法通过list+hash的方式进行实现
  • 首先是链表节点的定义
class ListNode{
public:
    ListNode *pre, *next;
    int key, value;
    
    ListNode(int key, int value): key(key), value(value), pre(NULL), next(NULL){
        
    }
};
  • LRUCache具体实现如下这里面仅仅实现了get和set方法,其他方法省略。
class LRUCache{
private:
    int capacity;
    int size;
    map hash;
    ListNode *head, *tail;
public:
    LRUCache(int capacity): capacity(capacity), size(0){
        //头尾节点预先申请两个空间,减少指针的空值判断
        head = new ListNode(0, 0);
        tail = new ListNode(0, 0);
        head->next = tail;
        tail->pre = head;
    }
    
    int set(int key, int value){
        ListNode *temp = new ListNode(key, value);
        hash[key] = temp;
        temp->next = head->next;
        temp->pre = head;
        head->next = temp;
        ++size;
        if(size > capacity){
            ListNode *t = tail->pre;
            tail->pre = t->pre;
            t->pre->next = tail;
            delete(t);
            --size;
        }
    }
    
    int get(int key){
        if(hash.find(key) == hash.end()){
            return -1;//假设-1为异常值
        }
        ListNode *t = hash[key];
        t->pre->next = t->next;
        t->next->pre = t->pre;
        t->pre = head;
        t->next = head->next;
        head->next = t;
        return t->value;
    }
};

你可能感兴趣的:(c/c++/vc)