- LRUCache實現本方法通過list+hash的方式進行實現
- 首先是鏈表節點的定義
class ListNode{
public:
ListNode *pre, *next;
int key, value;
ListNode(int key, int value): key(key), value(value), pre(NULL), next(NULL){
}
};
- LRUCache具體實現如下這裏面僅僅實現了get和set方法,其他方法省略。
class LRUCache{
private:
int capacity;
int size;
map<int, ListNode*> hash;
ListNode *head, *tail;
public:
LRUCache(int capacity): capacity(capacity), size(0){
//頭尾節點預先申請兩個空間,減少指針的空值判斷
head = new ListNode(0, 0);
tail = new ListNode(0, 0);
head->next = tail;
tail->pre = head;
}
int set(int key, int value){
ListNode *temp = new ListNode(key, value);
hash[key] = temp;
temp->next = head->next;
temp->pre = head;
head->next = temp;
++size;
if(size > capacity){
ListNode *t = tail->pre;
tail->pre = t->pre;
t->pre->next = tail;
delete(t);
--size;
}
}
int get(int key){
if(hash.find(key) == hash.end()){
return -1;//假設-1爲異常值
}
ListNode *t = hash[key];
t->pre->next = t->next;
t->next->pre = t->pre;
t->pre = head;
t->next = head->next;
head->next = t;
return t->value;
}
};