leetcode 146. LRU Cache
class LRUCache {
private:
struct Node {
int key;
int val;
Node* prev;
Node* next;
Node(int k, int v):key(k), val(v), prev(NULL), next(NULL){}
Node() = default;
};
void removeLastNode(){
auto last = tail->prev;
last->prev->next = tail;
tail->prev = last->prev;
cache.erase(last->key);
delete last;
}
void insertHead(Node* node){
node->next = head->next;
head->next->prev = node;
head->next = node;
node->prev = head;
}
void detachNode(Node* node){
node->prev->next = node->next;
node->next->prev = node->prev;
}
Node* head;
Node* tail;
int cap;
unordered_map<int, Node*> cache;
public:
LRUCache(int capacity) {
head = new Node;
tail = new Node;
head->next = tail;
tail->prev = head;
cap = capacity;
}
int get(int key) {
if(cache.find(key) == cache.end()) return -1;
detachNode(cache[key]);
insertHead(cache[key]);
return cache[key]->val;
}
void put(int key, int value) {
if(cache.find(key) != cache.end()){
cache[key]->val = value;
detachNode(cache[key]);
} else {
Node* newNode = new Node(key, value);
if(cache.size() == cap) removeLastNode();
cache[key] = newNode;
}
insertHead(cache[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);
*/