Created
February 12, 2020 19:20
-
-
Save mg11111/ca9067993ba3ccb31b88664c75553ba7 to your computer and use it in GitHub Desktop.
LRUCache Implementation using abstract class C++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<bits/stdc++.h> | |
using namespace std; | |
struct Node{ | |
Node *next,*prev; | |
int key,value; | |
Node(Node *p,Node *n, int k,int v):prev(p),next(n),key(k),value(v){}; | |
Node(int k,int v):prev(NULL),next(NULL),key(k),value(v){}; | |
}; | |
class Cache { | |
protected: | |
map<int,Node*> hash; | |
int capacity; | |
Node *front,*rear; | |
virtual void set(int,int)=0; | |
virtual int get(int)=0; | |
}; | |
class LRUCache : Cache{ | |
public: | |
LRUCache(int n){ | |
capacity=n; | |
front=rear=NULL; | |
} | |
void set(int key,int value){ | |
Node *temp; | |
if(hash.empty()){ | |
temp= new Node(key,value); | |
front=rear=temp; | |
hash[key]=temp; | |
return; | |
}else if (hash.find(key)==hash.end()){ | |
Node *N=new Node(front->prev,front,key,value); | |
front->prev=N; | |
front=N; | |
hash[key]=N; | |
if(hash.size()>capacity){ | |
rear=rear->prev; | |
hash.erase(rear->next->key); | |
free(rear->next); | |
rear->next=NULL; | |
} | |
return; | |
}else{ | |
hash[key]->value=value; | |
if(hash[key]==front){ | |
return; | |
} | |
hash[key]->prev->next=hash[key]->next; | |
if(rear==hash[key]){ | |
rear=rear->prev; | |
}else{ | |
hash[key]->next->prev=hash[key]->prev; | |
} | |
hash[key]->next=front; | |
hash[key]->prev=NULL; | |
front->prev=hash[key]; | |
front=hash[key]; | |
return; | |
} | |
} | |
int get(int key){ | |
if(hash.find(key)!=hash.end()){ | |
return hash[key]->value; | |
} | |
return -1; | |
} | |
}; | |
int main() { | |
//dummy examples for input and output. | |
int n, capacity,i; | |
cin >> n >> capacity; | |
LRUCache l(capacity); | |
for(i=0;i<n;i++) { | |
string command; | |
cin >> command; | |
if(command == "get") { | |
int key; | |
cin >> key; | |
cout << l.get(key) << endl; | |
} | |
else if(command == "set") { | |
int key, value; | |
cin >> key >> value; | |
l.set(key,value); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment