/*
* Solution.cpp
*
* Created on: 2014年4月8日
* Author: William
*/
#include <iostream>
#include <map>
using namespace std;
struct Node {
int key;
int val;
Node *prev;
Node *next;
Node(int k, int v) :
key(k), val(v), prev(NULL), next(NULL) {
}
};
class LRUCache {
public:
int cap;
int cnt;
map<int, Node*> mp;
Node *head, *tail;
LRUCache(int capacity) {
if (capacity < 1) return;
cap = capacity;
cnt = 0;
mp.clear();
head = new Node(-1, -1);
tail = new Node(-1, -1);
head->next = tail;
tail->prev = head;
}
void putToHead(Node *p) {
p->next = head->next;
p->prev = head;
p->next->prev = p;
head->next = p;
}
int get(int key) {
map<int, Node*>::iterator it = mp.find(key);
if (it != mp.end()) {
Node *p = it->second;
p->prev->next = p->next;
p->next->prev = p->prev;
putToHead(p);
return p->val;
} else {
return -1;
}
}
void set(int key, int value) {
if (cap < 1) return;
map<int, Node*>::iterator it = mp.find(key);
if (it != mp.end()) {
Node *p = it->second;
p->prev->next = p->next;
p->next->prev = p->prev;
putToHead(p);
p->val = value;
} else {
Node *p = new Node(key, value);
mp.insert(pair<int, Node*>(key, p));
putToHead(p);
cnt++;
if (cnt > cap) {
p = tail->prev;
p->prev->next = tail;
tail->prev = p->prev;
mp.erase(p->key);
delete p;
cnt--;
}
}
}
};
//int main() {
// return 0;
//}
LRU Cache
最新推荐文章于 2024-10-14 18:43:42 发布