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.
Simple implementation avoiding pointer swapping hell. Getting LRU logic right is key here.
classLRUCache:publicCache{voidremoveBack(){Node*currTail=tail;Node*newTail=tail->prev;intkey=currTail->key;mp.erase(key);if(newTail)newTail->next=NULL;elsehead=NULL;deletecurrTail;}voidaddNodeFront(intkey,intval){if(head){Node*newNode=newNode(NULL,head,key,val);if(mp.size()==cp)removeBack();head->prev=newNode;head=newNode;mp[key]=newNode;// Update mapping}else{Node*newNode=newNode(key,val);tail=head=newNode;mp[key]=newNode;}}voidmoveToHead(Node*arg,intnewVal){Node*next,*prev;arg->value=newVal;// Update valueif(arg==head)return;// If already head do nothingnext=arg->next;prev=arg->prev;if(prev)// If previous is not NULLprev->next=next;if(next)// Same for nextnext->prev=prev;head->prev=arg;if(arg==tail)tail=arg->prev;arg->next=head;arg->prev=NULL;head=arg;}public:LRUCache(constint&cap){cp=cap;}voidset(intkey,intvalue){if(mp.find(key)!=mp.end()){if(mp.size()>1)moveToHead(mp[key],value);elsehead->value=value;}elseaddNodeFront(key,value);}intget(intkey){if(mp.find(key)!=mp.end()){moveToHead(mp[key],mp[key]->value);// W or w/o passess all testsreturnmp[key]->value;}elsereturn-1;}};
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 →
Simple implementation avoiding pointer swapping hell. Getting LRU logic right is key here.