my solution runs fine on test but runtime error on submit. why?


  • 0
    A
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode *l1curr=l1, *l2curr=l2,*lres,*lrescurr;
        int res=0;
        lres=malloc(sizeof(struct ListNode));
        lrescurr=lres;
        while(l1curr || l2curr){
            res+=(((l1curr)?l1curr->val:0)+((l2curr)?l2curr->val:0));
            lrescurr->val=res%10;
            res/=10;
            if(l1curr) l1curr=l1curr->next;
            if(l2curr) l2curr=l2curr->next;
            if(l1curr || l2curr || res>0){
                lrescurr->next=malloc(sizeof(struct ListNode));
                lrescurr=lrescurr->next;
            }
    
        }
        if(res>0){
            lrescurr->val=1;
        }
        return lres;
    }
    

  • 1

    @alejandroerickson In C, you have to explicitly set the next to NULL which will not be automatically handled as C++. Your solution can then be easily fixed as follows.

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode *l1curr=l1, *l2curr=l2,*lres,*lrescurr;
        int res=0;
        lres=malloc(sizeof(struct ListNode));
        lres->next = NULL;
        lrescurr=lres;
        while(l1curr || l2curr){
            res+=(((l1curr)?l1curr->val:0)+((l2curr)?l2curr->val:0));
            lrescurr->val=res%10;
            res/=10;
            if(l1curr) l1curr=l1curr->next;
            if(l2curr) l2curr=l2curr->next;
            if(l1curr || l2curr || res>0){
                lrescurr->next=malloc(sizeof(struct ListNode));
                lrescurr=lrescurr->next;
                lrescurr->next = NULL;
            }
    
        }
        if(res>0){
            lrescurr->val=1;
        }
        return lres;
    }
    

  • 0
    A

    Aha! Thank you, I had forgotten that.


Log in to reply
 

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