标签:存储 表示 节点 tor lrucache 思路 链表 etc 更新
struct Node {
int key; //为了删除节点时,同时删除hash表中的key
int val;
Node *next;
Node *prev;
Node(int k, int v){
key = k;
val = v;
next = NULL;
prev = NULL;
}
};
class LRUCache {
public:
LRUCache(int capacity) {
size = capacity;
//哑节点可以化解很多异常情况
Node *dummy1 = new Node(-1, -1);
Node *dummy2 = new Node(-1, -1);
head = dummy1;
tail = dummy2;
head->next = dummy2;
tail->prev = dummy1;
}
int get(int key) {
map<int, Node*>::iterator iter;
iter = table.find(key);
if(iter != table.end()){
Node *cur = iter->second;
//从当前位置摘掉
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
//将该节点插入头部
cur->next = head->next;
cur->prev = head;
head->next->prev = cur;
head->next = cur;
return cur->val;
}
return -1;
}
void put(int key, int value) {
if(get(key) > 0){
//更新已存在key的value
// head->next->val = value;
table[key]->val = value;
return;
}
//当容量为0时,先删除,再插入
if(size == 0){
Node *del_node = tail->prev;
del_node->next->prev = del_node->prev;
del_node->prev->next = del_node->next;
del_node->prev = NULL;
del_node->next = NULL;
//先删除hash表中的key,再删除节点
table.erase(del_node->key);
delete del_node;
size++;
}
Node *node = new Node(key, value);
//将其插入头部
node->next = head->next;
node->prev = head;
head->next->prev = node;
head->next = node;
table[key] = node;
size--;
}
private:
map<int, Node*> table;
int size;
Node *head;
Node *tail;
};
标签:存储 表示 节点 tor lrucache 思路 链表 etc 更新
原文地址:https://www.cnblogs.com/wengle520/p/12336341.html