class LRUCache{
private:
class node{
public:
int key;
int val;
node* prev;
node* next;
node(int key, int val) {
this->key = key;
this->val = val;
this->prev = NULL;
this->next = NULL;
}
};
node* head = NULL;
node* tail = NULL;
unordered_map<int, node*> map;
int capacity;
void moveToTail(node* current) {
tail->prev->next = current;
current->prev = tail->prev;
current->next = tail;
tail->prev = current;
return;
}
public:
LRUCache(int capacity) {
this->capacity = capacity;
this->head = new node(-1, -1);
this->tail = new node(-1, -1);
head->next = tail;
tail->prev = head;
}
int get(int key) {
if (map.find(key) == map.end()) {
return -1;
}
node* current = map[key];
current->prev->next = current->next;
current->next->prev = current->prev;
moveToTail(current);
return current->val;
}
void set(int key, int value) {
if (get(key) != -1) {
map[key]->val = value;
return;
}
if (map.size() == capacity) {
node* oldestNode = head->next;
map.erase(oldestNode->key);
oldestNode->next->prev = head;
head->next = oldestNode->next;
delete oldestNode;
}
node* newNode = new node(key, value);
map.insert({key, newNode});
moveToTail(newNode);
return;
}
};