您的位置:首页 > 其它

LRU Cache

2015-07-24 16:39 337 查看
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.

struct node{
int key;
int value;
node* pre;
node* next;
};
class LRUCache{
private:
int count;
int size;
map<int,node*> mp;
node* cachehead;
node* cachetail;
public:
LRUCache(int capacity) {
count=0;
size=capacity;

cachehead=NULL;
cachetail=NULL;
}

int get(int key) {
if(cachehead==NULL) return -1;
map<int,node*>::iterator it=mp.find(key);
if(it==mp.end())
return -1;
else
{
node* p=it->second;
pushfront(p);
//p->pre->next=p->next;
/*if(p->next!=NULL)
p->next->pre=p->pre;
mp.erase(p->key);
p->next=cachehead;
p->pre=cachehead->pre;
cachehead->pre=p;
cachehead=cachehead->pre;
mp[cachehead->key]=cachehead;*/

}
return cachehead->value;
}

void set(int key, int value) {
if(cachehead==NULL)
{
cachehead=(node*)malloc(sizeof(node));
cachehead->key=key;
cachehead->value=value;
cachehead->pre=NULL;
cachehead->next=NULL;
mp[key]=cachehead;
cachetail=cachehead;
count++;
}
else
{
map<int,node*>::iterator it=mp.find(key);
if(it==mp.end())
{
if(count==size)
{
if(cachehead==cachetail&&cachehead!=NULL)
{
mp.erase(cachehead->key);
cachehead->key=key;
cachehead->value=value;
mp[key]=cachehead;
}
else
{
node* p=cachetail;
cachetail->pre->next=cachetail->next;
cachetail=cachetail->pre;

mp.erase(p->key);

p->key=key;
p->value=value;

p->next=cachehead;
p->pre=cachehead->pre;
cachehead->pre=p;
cachehead=p;
mp[cachehead->key]=cachehead;
}

}
else
{
node* p=(node*)malloc(sizeof(node));
p->key=key;
p->value=value;
p->next=cachehead;
p->pre=cachehead->pre;
cachehead->pre=p;
cachehead=p;
mp.erase(p->key);
mp[cachehead->key]=cachehead;
count++;
}
}
else
{

node* p=it->second;
p->value=value;
pushfront(p);
/*   mp.erase(p->key);

p->pre->next=p->next;
if(p->next!=NULL)
p->next->pre=p->pre;
p->value=value;
p->next=cachehead;
p->pre=cachehead->pre;
cachehead->pre=p;
cachehead=cachehead->pre;
mp[cachehead->key]=cachehead;*/
}
}

}
void pushfront(node* cur)
{
if(count==1)
return;
if(cur==cachehead) return;
if(cur==cachetail)
cachetail=cur->pre;
cur->pre->next=cur->next;
if(cur->next!=NULL)
cur->next->pre=cur->pre;
cur->next=cachehead;
cur->pre=cachehead->pre;
cachehead->pre=cur;
cachehead=cur;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: