struct DList { int key, value; DList *next, *pre; DList() : key(0), value(0), next(nullptr), pre(nullptr) {} DList(int _key, int _value) : key(_key), value(_value), next(nullptr), pre(nullptr) {} }; class LRUCache { private: int cap, nowSize = 0; map<int, DList *> mp; DList *head; DList *tail; void move_to_head(DList *node) { remove(node); add_to_head(node); } void remove(DList *node) { DList *Pre = node->pre; DList *Next = node->next; Pre->next = Next; Next->pre = Pre; } void add_to_head(DList *node) { DList *Sec = head->next; Sec->pre = node; node->next = Sec; head->next = node; node->pre = head; } public: LRUCache(int capacity) { mp.clear(); cap = capacity; head = new DList(); tail = new DList(); head->next = tail; tail->pre = head; } int get(int key) { if (!mp.count(key)) { return -1; } else { DList *node = mp[key]; move_to_head(node); return node->value; } } void put(int key, int value) { if (!mp.count(key)) { DList *node = new DList(key, value); add_to_head(node); nowSize++; mp[key] = node; if (nowSize > cap) { mp.erase(tail->pre->key); remove(tail->pre); nowSize--; } } else { DList *node = mp[key]; node->value = value; move_to_head(node); } } }; /** * 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); */
对封装的一些见解