146. LRU 缓存
数据结构:双向链表、哈希表–> 哈希链表
class Node{
public:
int key,value;
Node * next, *pre;
Node(int k, int v)
{
key = k;
value = v;
next = NULL;
pre = NULL;
}
};
class Doublelist{
private:
/* 头尾虚节点 */
Node *head,*tail;
public:
/* 节点数量 */
int size;
Doublelist()
{
head = new Node(0,0);
tail = new Node(0,0);
head->next = tail;
tail->pre = head;
size =0;
}
/* 插入到头结点之后 */
/* 既然是头结点之后,过程中不能出现尾节点 */
void Insert_first(Node *nod)
{
nod->next = head->next;
nod->pre = head->next->pre;
head->next->pre = nod;
head->next = nod;
size++;
}
/* 插入成为尾节点 */
void Insert_last(Node *x)
{
x->next = tail->pre->next;
x->pre = tail->pre;
tail->pre->next = x;
tail->pre = x;
size++;
}
/* 删除第一个节点 */
Node* remove_first(void)
{
if(head->next == tail)
{
return NULL;
}
Node *p1 = head->next;
Node *p = head->next->next;
head->next = p;
p->pre = head;
size--;
return p1;
}
/* 删除最后一个节点 */
Node* remove_last(void)
{
if(head->next == tail)
{
return NULL;
}
Node *p = tail->pre;
Node *p1=tail->pre->pre;
p1->next = tail;
tail->pre = p1;
size--;
return p;
}
/* 删除x节点*/
void remove_x(Node* x)
{
Node* p1= x->pre;
Node* p2= x->next;
p1->next = p2;
p2->pre = p1;
size--;
}
};
class LRUCache {
private:
int cap;
public:
map<int,Node*> maping;
Doublelist *cache;
LRUCache(int capacity) {
cap = capacity;
//maping = *(new map());
cache = new Doublelist();
}
int get(int key) {
if(!maping.count(key))
{
return -1;
}
Node* p= maping[key];
active_top(key);
return p->value;
}
void put(int key, int value) {
if(maping.count(key))
{
Node *p = maping[key];
p->value = value;
active_top(key);
return;
}
if(cache->size == cap)
{
delete_oldest();
}
add_page(key,value);
}
/* 获得正在使用的页面标记,在哈希表中找到页面,
将页面移到队尾作为最新页面*/
void active_top(int key)
{
Node* p = maping[key];
cache->remove_x(p);
cache->Insert_last(p);
}
/* 添加指定页面 */
void add_page(int key, int value)
{
Node *x = new Node(key,value);
cache->Insert_last(x);
maping[key] = x;
}
/* 删除指定页面 */
void delete_page(int key)
{
Node* p = maping[key];
cache->remove_x(p);
maping.erase(key);
}
/* 删除最久未使用页面 */
void delete_oldest()
{
Node *p= cache->remove_first();
maping.erase(p->key);
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/