如何设计一个简单的cache系统

44 篇文章 0 订阅

如何设计一个简单的cache系统  (LRU)

2014-06-03 16:29:44|  分类: 默认分类|举报|字号 订阅

struct node{
node* pre;
int key;
int value;
node* next;
node(int k, int v):key(k),value(v),pre(NULL),next(NULL){};
};

class LRUCache{
unordered_map<int, node*> mp;
int capacity;
int size;
node* head;
node* tail;
public:
LRUCache(int c){
if(c<0)return;
head = new node(-1,-1);
tail = new node(-1,-1);
head->next = tail;
tail->pre = head;
mp.clear();
capacity = c;
size = 0;
}
    
int get(int k) {
unordered_map<int, node*>::iterator it = mp.find(k);
if(it != mp.end()){
node* p = it->second;
p->pre->next = p->next;
p->next->pre = p->pre;
putToHead(p);
return p->value;
}
else
return -1;
}
    
void set(int k, int val) {
if(capacity < 1) return; 
unordered_map<int, node*>::iterator it = mp.find(k);
if(it != mp.end()){
node* p = it->second;
p->pre->next = p->next;
p->next->pre = p->pre;
putToHead(p);
p->value = val;
}else{
node* p = new node(k, val);
putToHead(p);
mp[k] = p;
size++;
if(size>capacity){
p = tail->pre;
tail->pre = p->pre;
p->pre->next = tail;
it = mp.find(p->key);
mp.erase(it);
delete p;
}
}
}

void putToHead(node* p)
{
p->next = head->next;
p->pre = head;
head->next->pre = p;
head->next = p;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值