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.
My solution - I'm not a professional c++ dev but this was fun
classLRUCache:publicCache{private:intcapacity;voidmove_node_to_head(Node*node);voidremove_node_from_tail(Node*node);public:LRUCache(intcapacity);intget(intkey);voidset(intkey,intvalue);};LRUCache::LRUCache(intcapacity){this->tail=nullptr;this->head=nullptr;this->capacity=capacity;}intLRUCache::get(intkey){if(mp[key]==nullptr){return-1;}intcache_entry=mp[key]->value;move_node_to_head(mp[key]);returncache_entry;}voidLRUCache::move_node_to_head(Node*new_head_node){// In case we are getting or setting a value at the headif(head==new_head_node){return;}// IN case its the very first insert, we set head = tailif(tail==nullptr){tail=new_head_node;}if(head==nullptr){head=new_head_node;mp[new_head_node->key]=new_head_node;return;}if(tail->prev==nullptr){tail->prev=head;}/** * N1 -> next | prv <- N2 -> next * We take the currrent head and move it to the next position, so the new head node next, will point to the current head node previous node */new_head_node->next=head;new_head_node->prev=nullptr;// A head doesn't have any previous nodehead=new_head_node;mp[new_head_node->key]=new_head_node;}/** * Need to remove the tail node and shifting the nodes to the right */voidLRUCache::remove_node_from_tail(Node*node){if(tail==nullptr){return;}Node*old_tail=tail;if(tail->prev!=nullptr){tail->prev->next=nullptr;// remove the tail also from the node before}mp.erase(tail->key);deleteold_tail;}voidLRUCache::set(intkey,intvalue){Node*new_node=newNode(key,value);// first entry in the listif(mp[key]!=nullptr){// the Node is existing, so we update the value move to the headNode*node=mp[key];node->value=value;move_node_to_head(new_node);}else{// Cache is fullif(mp.size()>this->capacity){// remove node from tailremove_node_from_tail(new_node);}move_node_to_head(new_node);}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Abstract Classes - Polymorphism
You are viewing a single comment's thread. Return to all comments →
My solution - I'm not a professional c++ dev but this was fun