We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<iostream>#include<vector>#include<map>#include<string>#include<algorithm>#include<set>#include<cassert>usingnamespacestd;structNode{Node*next;Node*prev;intvalue;intkey;Node(Node*p,Node*n,intk,intval):prev(p),next(n),key(k),value(val){};Node(intk,intval):prev(NULL),next(NULL),key(k),value(val){};};classCache{protected:map<int,Node*>mp;//map the key to the node in the linked listintcp;//capacityNode*tail;// double linked list tail pointerNode*head;// double linked list head pointervirtualvoidset(int,int)=0;//set functionvirtualintget(int)=0;//get function};classLRUCache:publicCache{public:LRUCache(intc){cp=c;head=nullptr;}voidset(intkey,intvalue){if(mp.size()==0){head=mp[key]=newNode(key,value);}elseif(mp.size()>=cp){mp.erase(mp.find(head->key));mp[key]=newNode(key,value);}else{mp[key]=newNode(key,value);}}intget(intkey){map<int,Node*>::iteratorit=mp.find(key);if(it!=mp.end()){returnit->second->value;}return-1;}};intmain(){intn,capacity,i;cin>>n>>capacity;LRUCachel(capacity);for(i=0;i<n;i++){stringcommand;cin>>command;if(command=="get"){intkey;cin>>key;cout<<l.get(key)<<endl;}elseif(command=="set"){intkey,value;cin>>key>>value;l.set(key,value);}}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Abstract Classes - Polymorphism
You are viewing a single comment's thread. Return to all comments →
hold my beer implementation: