diff --git a/lruCache b/lruCache new file mode 100644 index 0000000..bd586f2 --- /dev/null +++ b/lruCache @@ -0,0 +1,80 @@ +struct Node{ + int key; + int value; + Node *next; + Node *prev; + Node(int x,int y){ + key = x; + value= y; + } +}; +class LRUCache +{ + private: + unordered_map mp; + public: + Node *head = NULL; + Node *tail = NULL; + int capacity; + int c = 0; + LRUCache(int cap){ + capacity = cap; + } + int get(int key){ + if(mp.find(key) == mp.end()) + return -1; + if(key == tail->key) + return tail->value; + Node * temp = mp[key]; + if(key == head->key){ + Node *t = head; + head = head->next; + head->prev = NULL;t->next = NULL; + tail->next = t;t->prev = tail;tail = tail->next; + return temp->value; + } + temp->prev->next = temp->next; + temp->next->prev = temp->prev; + temp->next = NULL;temp->prev =NULL; + tail->next = temp; + temp->prev =tail; + tail = tail->next; + return tail->value; + } + void set(int key, int value) + { + Node *temp = new Node(key,value); + if(mp.find(key) != mp.end()){ + Node *t = mp[key]; + if(t == tail){ + tail->value = value;mp[key] = tail; return;} + else if(t == head){ + head = head->next;head->prev = NULL;t->next = NULL; + } + else{ + t->prev->next = t->next;t->next->prev = t->prev;t->next = t->prev = NULL; + } + tail->next = temp;temp->prev = tail; + tail = tail->next; + mp[key] = temp; + return; + } + c++; + mp[key] = temp; + if(!head){ + head = temp; + tail = temp; + return; + } + tail->next = temp; + temp->prev = tail; + tail = tail->next; + if(c > capacity){ + Node *t = head; + mp.erase(t->key); + head= head->next; + head->prev = NULL; + t->next = NULL; + c--; + } + }