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.
//本题置换算法LRU,对节点的访问都将被提到栈顶。(get,set)。
//本题细节较多!我弄错了很多地方!以下代码已通过!
struct Node
{
int key,data;
struct Node *next;
struct Node *pre;
};
class LRUCache{
public:
LRUCache(int capacity)
{
num = 0;
max_capacity = capacity;
base = top = NULL;
}
int get(int key)
{
Node *pnode = top;
while(pnode != NULL)
{
if (pnode->key == key)
{
if (pnode == top)//当为栈顶,直接返回
{
return top->data;
}
if (pnode->next == NULL)//当为末尾元素,的注意
{
if (pnode->pre == NULL)
{
return pnode->data;
}
//处理需找的元素的上一节点
base = pnode->pre;
pnode->pre->next = NULL;
}
if (pnode->next)//中间元素处理
{
pnode->pre->next = pnode->next;
pnode->next->pre = pnode->pre;
}
//提到栈顶
pnode->next = top;
pnode->pre = NULL;
top->pre = pnode;
top = pnode;
return pnode->data ;
}
pnode = pnode->next;
}
return -1;
}
void set(int key, int value)
{
Node *pnode;
if (top == NULL&&base == NULL)//第一个节点加入
{
pnode= new Node;
pnode->key =key;
pnode->data = value;
top = base = pnode;
top->pre = NULL;
base->next =NULL;
num ++;
return ;
}
if(get(key) != -1)//找到
{
top->data = value;
return ;
}
//没找到
if (num >= max_capacity)
{
if(num == 1)//一个节点不用管
{
top->key =key;
top->data = value;
return ;
}
pnode = base->pre;
pnode->next = NULL;
delete base;
base = pnode;
num--;
}
//加入栈顶
if (num < max_capacity)
{
pnode = new Node;
pnode->key =key;
pnode->data = value;
pnode->next = top;
pnode->pre = NULL;
top->pre = pnode;
top = pnode;//增加top
num++;
}
}
private:
int max_capacity;
Node *base;
Node *top;
int num;
};