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.
classLRUCache:publicCache{Node*ptr_bf{};public:LRUCache(intcapacity){cp=capacity;tail=nullptr;head=nullptr;}~LRUCache(){while(head!=nullptr){ptr_bf=head->next;deletehead;head=ptr_bf;}}voidset(intk,intv){if(mp.find(k)!=mp.end()){// if key foundptr_bf=mp[k];ptr_bf->value=v;if(ptr_bf->prev!=nullptr){if(ptr_bf->next==nullptr){// if last element in linked listtail=ptr_bf->prev;ptr_bf->prev->next=nullptr;}else{// else if not lastptr_bf->prev->next=ptr_bf->next;ptr_bf->next->prev=ptr_bf->prev;}ptr_bf->prev=nullptr;ptr_bf->next=head;head=mp[k];}}else{// if key not foundif(mp.empty()){// if size of map is 0Node*new_node=newNode(k,v);mp[k]=new_node;head=new_node;tail=new_node;}elseif(mp.size()>=cp){// if size of map reach max capacity//pop lastmp.erase(tail->key);ptr_bf=tail->prev;deletetail;tail=ptr_bf;tail->next=nullptr;//add newNode*new_node=newNode(nullptr,head,k,v);mp[k]=new_node;head->prev=new_node;head=new_node;}else{// if size of map normalNode*new_node=newNode(nullptr,head,k,v);mp[k]=new_node;head->prev=new_node;head=new_node;}}}intget(intk){if(mp.find(k)!=mp.end()){// if key is presentreturnmp[k]->value;}else{// if key not presentreturn-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 →