LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

 

Code:

class LRUCache{
private:
    struct ListNode {
        int key;
        int val;
        ListNode *last;
        ListNode *next;
        ListNode(int x, int y) : key(x), val(y), last(NULL),next(NULL) {}
    };
    int capacity,len;
    map <int,ListNode*> cacheMap;
    ListNode *anchor;
    
public:
    
    LRUCache(int capacity) {
        this->capacity=capacity;
        len=0;
        anchor = new ListNode(0,0);
        anchor->next=anchor;
        anchor->last=anchor;
    }
    
    int get(int key) {
        ListNode *cur=cacheMap[key];
        if(cur==NULL)
            return -1;
        moveOut(cur); // move out from list
        append(cur); // update
        return cur->val;
    }
    
    void set(int key, int value) {
        if(cacheMap[key]){ // set
            ListNode *cur=cacheMap[key];
            cur->val=value; // set a new value
            moveOut(cur); // move out from list
            append(cur); // update
            
        }else{ //insert
            if(len==capacity)
                drop(); // if full, drop the LRU           
            ListNode *cur = new ListNode(key,value); // create a new node
            append(cur); // append the new node
            cacheMap[key]=cur; // update the map
            len++;
        }
    }
    
    void moveOut(ListNode *cur){
        cur->last->next=cur->next;
        cur->next->last=cur->last;
    }
    
    void append(ListNode *cur){
        anchor->last->next=cur;
        cur->last=anchor->last;
        anchor->last=cur;
        cur->next=anchor;
    }
    
    void drop(){
        ListNode *del = anchor->next;
        anchor->next->next->last=anchor;
        anchor->next=anchor->next->next;
        cacheMap.erase(del->key);
        delete del;
        len--;
    }
    
};

 

posted @ 2013-11-13 17:45  WinsCoder  阅读(167)  评论(0编辑  收藏  举报