Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create LRU-cache(Doubly-linked-list).cpp #6756

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
73 changes: 73 additions & 0 deletions LRU-cache(Doubly-linked-list).cpp
@@ -0,0 +1,73 @@
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
int key;
int value;
Node *next;
Node *prev;

Node(int k, int v) : key(k), value(v) {
next = nullptr;
prev = nullptr;
}
};

class LRUCache {
public:
int capacity;
unordered_map<int, Node*> mp; // map the key to the node in the linked list
Node *head;
Node *tail;

LRUCache(int c) : capacity(c) {
head = new Node(0, 0);
tail = new Node(0, 0);
head->next = tail;
tail->prev = head;
head->prev = nullptr;
tail->next = nullptr;
}

void addNode(Node *node) {
node->next = head->next;
head->next->prev = node;
node->prev = head;
head->next = node;
}

void removeNode(Node *node) {
node->prev->next = node->next;
node->next->prev = node->prev;
}

void moveToHead(Node *node) {
removeNode(node);
addNode(node);
}

int get(int key) {
if (mp.find(key) == mp.end())
return -1;
Node *node = mp[key];
moveToHead(node);
return node->value;
}

void put(int key, int value) {
if (mp.find(key) != mp.end()) {
Node *node = mp[key];
node->value = value;
moveToHead(node);
} else {
if (mp.size() == capacity) {
mp.erase(tail->prev->key);
removeNode(tail->prev);
}
Node *node = new Node(key, value);
addNode(node);
mp[key] = node;
}
}
};