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.
Here is an easy solution, correctly done, with head, tail, etc. and also deleting the pointers, not simply removing them from the map 'mp':
classLRUCache:Cache{public:LRUCache(intcapacity){this->cp=capacity;}voidinsert_node(intk,Node*node){//Set headthis->head=node;if(mp.empty())this->tail=node;//Set tailelsenode->next=mp.begin()->second;//Set next node//Insert new nodemp.insert(mp.begin(),std::pair<int,Node*>(k,node));if(node->next!=nullptr)node->next->prev=node;}voidset(intk,intv){Node*node=newNode(k,v);std::map<int,Node*>::iteratorduplicate=this->mp.find(k);//If key existsif(duplicate!=this->mp.end()){//Remove old keyif(node->next!=nullptr)node->next->prev=node->prev;if(node->prev!=nullptr){node->prev->next=node->next;if(node->next==nullptr)this->tail=node->prev;}delete(mp.at(k));mp.erase(k);//Insert at 0insert_node(k,node);}else{//If size is at max capacityif(this->mp.size()==this->cp){//Remove tailif(this->tail->prev!=nullptr)this->tail->prev->next=nullptr;delete(this->tail);mp.erase(this->tail->key);}//Insert at 0insert_node(k,node);}}intget(intk){return(this->mp.find(k)!=this->mp.end())?this->mp.at(k)->value:-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 →
Here is an easy solution, correctly done, with head, tail, etc. and also deleting the pointers, not simply removing them from the map 'mp':