Why my code is giving runtime error ?


  • 0
    R

    Hi, I have checked previous codes in discuss which were giving runtime error but I could not find out why my code is giving error on test : { 2,[set(2,1),set(3,2),get(3),get(2),set(4,3),get(2),get(3),get(4)] }

    Below is my Code:

    typedef struct Listnode{
        int key;
        int value;
        Listnode* next,*prev;
        Listnode(int k=0,int v=0){
            key=k;
            value=v;
            next=prev=NULL;
        }
    }Listnode;
    
    class LRUCache{
    public:
        int n;
        int size;
        Listnode *head,*tail;
        LRUCache(int capacity) {
            n=capacity;
            size=0;
            head=tail=NULL;
        }
        
        int get(int key) {
            if(size==0)return -1;
            Listnode* it=head;
            for(;it!=NULL;it=it->next){
                
                if(it->key==key){
                    break;
                }
            }
            
            if(it==NULL)return -1;
            if(it->prev==NULL)return it->value;
            it->prev->next=it->next;
            
            if(it->next==NULL)tail=it->prev;
            else it->next->prev=it->prev;
            it->next=head;
            head->prev=it;
            head=it;
            return it->value;
        }
        
        void set(int key, int value) {
                if(get(key)==-1){
                    Listnode* t=new Listnode(key,value);
                    if(size==n){
                        Listnode* temp=tail;
                        tail=tail->prev;
                        free(temp);
                        --size;
                    }
                        if(tail==NULL){
                            head=tail=t;
                        }
                        else {
                            t->next=head;
                            head->prev=t;
                            head=t;
                        }
                        ++size;
                    
                }
                else {
                    head->value=value;
                }
        }
    };

  • 0
    J
    1. memory leaks due to ListNodes not freed after the LRUCache object is destroyed
    2. should use delete instead of free for memory allocated by new
    3. after dropping the tail node, tail->prev->next still points to an invalid address

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.