Doubly linked list with map but gives different solution which I think is actually correct


#1
struct node {
    int mykey;
    int myvalue;
    struct node* next;
    struct node* previous;
};

int mycapacity = 0;
unordered_map<int,struct node*> mymap;
struct node* head;
struct node* last;

LRUCache::LRUCache(int capacity) {
    mymap.clear();
    mycapacity = capacity;
    head = new struct node;
    head->mykey = -1;
    head->myvalue = -1;
    head->next = NULL;
    head->previous = NULL;
    last = head;
}

int LRUCache::get(int key) {
    if(mymap.find(key)==mymap.end()) {
        return -1;
    } else {
        return mymap[key]->myvalue;
    }
}

void LRUCache::set(int key, int value) {
    if(mymap.find(key)!=mymap.end()) {

        if(mymap[key]==head) {
            head = head->next;
            head->previous = NULL;
            delete mymap[key];
            mymap.erase(key);
        } else {
            struct node* temp1 = mymap[key]->previous;
            struct node* temp2 = mymap[key]->next;

            temp1->next = temp2;
            temp2->previous = temp1;
            delete mymap[key];
            mymap.erase(key);

        }
        ///
        struct node* temp = last;
        last->mykey = key;
        last->myvalue = value;
        mymap[key] = last;
        last->next = new struct node;
        last = last->next;
        last->mykey = -1;
        last->myvalue = -1;
        last->next = NULL;
        last->previous = temp;
        return;
    }
    if(mymap.size()>=mycapacity) {
        mymap.erase(head->mykey);
        struct node* temp = head;
        head = head->next;
        delete temp;
    }
    struct node* temp = last;
    last->mykey = key;
    last->myvalue = value;
    mymap[key] = last;
    last->next = new struct node;
    last = last->next;
    last->mykey = -1;
    last->myvalue = -1;
    last->next = NULL;
    last->previous = temp;
}