https://oj.leetcode.com/problems/lru-cache/
涨姿势的一道题,相当于实现一种数据结构,实现最近最少使用数据结构。
// 用来记录 前后节点都是什么 类似链表上的节点 struct DataNode{ int key, value; DataNode *prev, *next; DataNode(int _key, int _value){ key = _key; value = _value; prev = NULL; next = NULL; } }; class LRUCache{ public: int capacity; DataNode *head; DataNode *tail; //用来快速查找,key在不在。本来用stack最自然了,但是它不支持中间位置的删除元素操作 map<int,DataNode*> cache; LRUCache(int capacity) { this->capacity = capacity; head = NULL; tail = NULL; } void moveToHead(DataNode *p) { if(p == head) // p is head return; if(p == tail) { tail = p->prev; tail->next = NULL; p->prev = NULL; p->next = head; head->prev = p; head = p; } else { p->prev->next = p->next; p->next->prev = p->prev; p->prev = NULL; p->next = head; head->prev = p; head = p; } } //取得值,并把这个值的node挪到最前面,相当于使用了一次了 int get(int key) { if(cache.count(key) == 0) return -1; DataNode *p = cache[key]; moveToHead(p); return p->value; } //如果不存在,则插入到最前面。如果存在则设置值,并把这个值的node挪到最前面,相当于使用了一次了 void set(int key, int value) { if(cache.count(key) == 0) //本来不包含 { DataNode *p = new DataNode(key,value); cache.insert(make_pair(key,p)); if(head == NULL) { head = p; tail = p; } else // p is new head { p->prev = NULL; p->next = head; head->prev = p; head = p; } // remove tail if(cache.size() > capacity) { cache.erase(tail->key); tail = tail->prev; tail->next = NULL; } } else { DataNode *p = cache[key]; p->value = value; moveToHead(p); } } };