struct LinkedNode {
int key, value;
LinkedNode* prev;
LinkedNode* next;
LinkedNode() : key(0), value(0), prev(nullptr), next(nullptr) {}
LinkedNode(int _key, int _value) : key(_key), value(_value), prev(nullptr), next(nullptr) {}
};
class LRUCache {
private:
unordered_map<int, LinkedNode*> cache;
LinkedNode* head;
LinkedNode* tail;
int size;
int capacity;
void addToHead(LinkedNode* node) {
node->prev = head;
node->next = head->next;
head->next->prev = node;
head->next = node;
}
void removeNode(LinkedNode* node) {
node->prev->next = node->next;
node->next->prev = node->prev;
}
void moveToHead(LinkedNode* node) {
removeNode(node);
addToHead(node);
}
LinkedNode* removeTail() {
LinkedNode* node = tail->prev;
removeNode(node);
return node;
}
public:
LRUCache(int _capacity) : capacity(_capacity), size(0) {
head = new LinkedNode();
tail = new LinkedNode();
head->next = tail;
tail->prev = head;
}
int get(int key) {
// if key does not exist, return -1
if (!cache.count(key)) return -1;
// if key exists, use hash map to locate, and move to head
LinkedNode* node = cache[key];
moveToHead(node);
return node->value;
}
void put(int key, int value) {
if (!cache.count(key)) {
// if key does not exist, create a new node
LinkedNode* node = new LinkedNode(key, value);
// add to hash map
cache[key] = node;
// add to head of double linked list
addToHead(node);
size++;
if (size > capacity) {
// delete tail node if size is larger than capacity
LinkedNode* removed = removeTail();
cache.erase(removed->key);
delete removed;
size--;
}
} else {
// if key exists, locate through hash map and move the modified node to head
LinkedNode* node = cache[key];
node->value = value;
moveToHead(node);
}
}
};
/**
* 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);
*/