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.
I had a little troubles with time errors, but i fixed it using mp.erase() function the less possible, moving the nodes "manually". Here's my working code. I hope you find it usefull.
classLRUCache:publicCache{public:LRUCache(intc){cp=c;}voidset(intk,intv){Node*N;if(mp.empty())//No nodes {N=newNode(k,v);tail=head=N;mp[k]=N;return;}autoit=mp.find(k);if(it!=mp.end())//In hash table{it->second->value=v;// update valueif(head==it->second)//head?return;it->second->prev->next=it->second->next;if(tail==it->second)//tail?tail=tail->prev;else//in between?it->second->next->prev=it->second->prev;it->second->next=head;it->second->prev=NULL;head->prev=it->second;head=it->second;}else// No in hash table{N=newNode(head->prev,head,k,v);//new nodehead->prev=N;head=N;mp[k]=N;if(mp.size()>cp)//capacity?{tail=tail->prev;mp.erase(tail->next->key);deletetail->next;tail->next=NULL;}}}intget(intk){autoit=mp.find(k);if(it!=mp.end())returnit->second->value;return-1;}};
Abstract Classes - Polymorphism
You are viewing a single comment's thread. Return to all comments →
I had a little troubles with time errors, but i fixed it using mp.erase() function the less possible, moving the nodes "manually". Here's my working code. I hope you find it usefull.