LRU实现记录
#include<iostream>
#include<unordered_map>
using namespace std;
class LRUCache {
private:
struct node {
int key;
int value;
node* left;
node* right;
node(int x, int y) :key(x), value(y), left(nullptr), right(nullptr) {}
};
int cap;
node* head = nullptr;
node* tail = nullptr;
unordered_map<int, node*>umap;
public:
LRUCache(int capacity) {
cap = capacity;
head = new node(0, 0);
tail = new node(0, 0);
head->right = tail;
tail->left = head;
}
~LRUCache() {
node* cur = head;
while (cur != nullptr) {
node* tmp = cur;
cur = cur->right;
delete tmp;
}
}
void push_list(node* n) {
n->left = head;
n->right = head->right;
head->right = n;
n->right->left = n;
}
void pop_list(node* n) {
n->left->right = n->right;
n->right->left = n->left;
}
void put(int key, int value) {
if (umap.count(key) == 0) {
node* newnode = new node(key, value);
push_list(newnode);
umap[key] = newnode;
if (umap.size() > cap) {
node* drop = tail->left;
umap.erase(drop->key);
pop_list(drop);
delete drop;
}
}
else {
umap[key]->value = value;
pop_list(umap[key]);
push_list(umap[key]);
}
}
int get(int key) {
if (umap.count(key) != 0) {
pop_list(umap[key]);
push_list(umap[key]);
cout << umap[key]->value << endl;
return umap[key]->value;
}
else {
cout << "找不到" << endl;
return -1;
}
}
};
int main() {
LRUCache* cache = new LRUCache(2);
cache->put(1, 1);
cache->put(2, 2);
cache->get(1);
cache->put(3, 3);
cache->get(2);
cache->put(4, 4);
cache->get(1);
cache->get(3);
cache->get(4);
return 0;
}