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 my simple implementation. Using sentinel nodes.
classLRUCache:publicCache{public:// Constructor: Initialize LRU cache with given capacityLRUCache(intcapacity){assert(capacity>0);// Capacity must be positivecp=capacity;// Initialize sentinel nodes (dummy head and tail)head=newNode(-1,-1);// Dummy head nodetail=newNode(-1,-1);// Dummy tail node// Link head and tail to form empty listtail->prev=head;head->next=tail;};// Destructor: Clean up all allocated nodes~LRUCache(){Node*p=head->next;while(p!=tail){Node*temp=p;p=p->next;deletetemp;// Delete all nodes including sentinels}deletehead;deletetail;}// Set key-value pair in cachevoidset(intkey,intval)override{// Step 1: Check if key existsautop=mp.find(key);if(p==mp.end()){// Step 2: If cache is full, evict LRU itemif(mp.size()==cp)popEnd();// Create new node and add to mapmp[key]=newNode(key,val);}else{// Update existing valuemp[key]->value=val;}// Step 3: Move node to front (MRU position)moveToFront(mp[key]);}// Get value by key, returns -1 if not foundintget(intkey)override{autop=mp.find(key);if(p==mp.end())return-1;// Move accessed node to front (MRU position)moveToFront(mp[key]);returnmp[key]->value;}private:// Move node to front of list (MRU position)voidmoveToFront(Node*curr){// If node is not new, remove from current positionif(curr->prev){curr->prev->next=curr->next;curr->next->prev=curr->prev;}// Insert node after head (new MRU position)Node*headNext=head->next;insertNode(head,headNext,curr);}// Helper to insert node between left and right nodesvoidinsertNode(Node*left,Node*right,Node*curr){left->next=curr;curr->prev=left;right->prev=curr;curr->next=right;}// Remove LRU item (node before tail)voidpopEnd(){Node*end=tail->prev;mp.erase(end->key);// Remove from map// Remove from listend->prev->next=tail;tail->prev=end->prev;deleteend;// Free memory}};
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 my simple implementation. Using sentinel nodes.