Abstract Classes - Polymorphism

  • + 0 comments

    This passes all tests while correctly maintaining both map and double linked Node list:

    class LRUCache : public Cache {
        public:
        LRUCache (int capacity){
            cp = capacity;
            tail = nullptr;
            head = nullptr;
        }
        
        int get(int key) override {
           if (mp.find(key) != mp.end()) return mp[key]->value;
           else return -1; 
        }
        
        void set (int key, int value) override{
            // Search key
            auto it = mp.find(key);
            // Hit
            if (it != mp.end()) it->second->value = value;
            // Miss
            else {
                if (mp.empty()){
                    mp[key] = new Node(key, value);
                    head = mp[key];
                    tail = head;
                }
                else if (mp.size() == cp) {
                    // Remove tail
                    Node *temp = tail->prev;
                    mp.erase(tail->key);
                    tail = temp;
                    tail->next = nullptr;
                    
                    // Add new Node as head
                    mp[key] = new Node(nullptr, head, key, value);
                    head->prev = mp[key];
                    head = mp[key];
                }
                else {
                    // Add new Node as head
                    mp[key] = new Node(nullptr, head, key, value);
                    head->prev = mp[key];
                    head = mp[key];
                }
            }
        }
    };