1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| struct DLinkedNode { int key, value; DLinkedNode* prev; DLinkedNode* next; DLinkedNode() : key(0), value(0), prev(nullptr), next(nullptr){}; DLinkedNode(int _key, int _value) : key(_key), value(_value), prev(nullptr), next(nullptr){}; }; class LRUCache { private: unordered_map<int, DLinkedNode*> cache; int size, capacity; DLinkedNode* head; DLinkedNode* tail; public: LRUCache(int _capacity) : size(0), capacity(_capacity) { head = new DLinkedNode(); tail = new DLinkedNode(); head->next = tail; tail->prev = head; } int get(int key) { if(!cache.count(key)) { return -1; } DLinkedNode* node = cache[key]; moveToHead(node); return node->value; } void put(int key, int value) { if(!cache.count(key)) { DLinkedNode* node = new DLinkedNode(key, value); cache[key] = node; addToHead(node); size++; if(size > capacity) { DLinkedNode* remove = tail->prev; cache.erase(remove->key); removeTail(); size--; delete remove; } } else { DLinkedNode* node = cache[key]; node->value = value; moveToHead(node); } } void addToHead(DLinkedNode* node) { node->prev = head; node->next = head->next; head->next->prev = node; head->next = node; } void removeNode(DLinkedNode* node) { node->next->prev = node->prev; node->prev->next = node->next; } void moveToHead(DLinkedNode* node) { removeNode(node); addToHead(node); } DLinkedNode* removeTail() { DLinkedNode* node = tail->prev; removeNode(node); return node; } };
|