Memory Limit exceeded


  • 0
    N

    Could someone please tell why i'm getting memory limit exceded for the below c++ code
    ......

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        int sum = 0,carry  = 0;
    
        struct ListNode * ans = NULL;
        struct ListNode * prev = NULL;
        struct ListNode* temp = NULL;
        while(l1 || l2)
        {
            //ans = (ListNode*)malloc(sizeof(ListNode));
            
            sum = l1->val + l2->val + carry;
            carry = sum/10;
            sum = sum % 10 ;
            temp = (struct ListNode*)malloc(sizeof(struct ListNode));
            temp->val = sum;
            temp->next = NULL;
            if(!ans)
                ans = temp;
            else
                prev->next = temp;
                
            prev = temp;
    
          if(l1->next)
            l1 = l1->next;
          if(l2->next)
            l2 = l2->next;
        }
        if(carry)
        {
            temp = (struct ListNode*)malloc(sizeof(struct ListNode));
            temp->val = carry;
            temp->next = NULL;
            prev->next = temp;
        }
        return  ans;
    

    }
    ....
    saw similar solutions submitted by other people which were accepted


  • 0
    V

    Because if you see carefully, you never let l1 and l2 become NULL, thus the while loop never terminates and you've malloc inside.


  • 0
    N

    Really thanks a lot !! Kept overlooking it :)


Log in to reply
 

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