自己实现LRU
这次是LeetCode146,这个代码做题可以通过但是有个问题就是最后设置的是默认析构,链表中的结点没有释放,造成了内存泄漏
struct node{ int key, value; node *prev; node *next; node(){ } node(int key, int value, node *prev = nullptr, node *next = nullptr){ this->key = key; this->value = value; this->prev = prev; this->next = next; } }; class LRUCache { private: int size, k; node *head; node *tail; map<int, node*> mp; void movetohead(node* n){ node* l = n->prev; node* r = n->next; l->next = r; r->prev = l; inserttohead(n); } void inserttohead(node* n){ node* r = head->next; head->next = n; n->prev = head; n->next = r; r->prev = n; } node* removetail(){ node* del = tail->prev; del->prev->next = tail; tail->prev = del->prev; return del; } public: LRUCache(int capacity) { size = 0; k = capacity; head = new node(); tail = new node(); head->next = tail; tail->prev = head; } int get(int key) { if(mp.count(key)){ movetohead(mp[key]); return mp[key]->value; } else return -1; } void put(int key, int value) { if(mp.count(key)){ mp[key]->value = value; movetohead(mp[key]); } else{ mp[key] = new node(key, value); inserttohead(mp[key]); size++; if(size > k) { node* del = removetail(); size--; mp.erase(del->key); delete del; } } }
~LRUCache(){
node *cur = head;
while(cur != tail){
node *tmp = cur;
cur = cur->next;
cur->prev = nullptr;
delete tmp;
}
}
}; /** * Your LRUCache object will be instantiated and called as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */

浙公网安备 33010602011771号