[C] runtime error with return correct case


  • 0
    J

    I tried to answer in C version,but why it returns runtime error with correct case?
    The algorithm is refer to https://leetcode.com/discuss/2308/is-this-algorithm-optimal-or-what

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *resultList = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *resultHead = resultList;
    int sum;
    int quot=0;
    int next_round = 1;
    while(next_round)
    {
        sum = 0;
        if(quot > 0)
        {
            sum += quot;
            quot = 0;
        }
    
        if(l1)
        {
            sum += l1->val;
            l1=l1->next;
        }
        if(l2)
        {
            sum += l2->val;
            l2=l2->next;
        }
        
        quot = (int)(sum/10);
        resultList->val = sum % 10;
        
        next_round = l1 || l2 || (quot > 0);
        if(next_round)
        {
            resultList = resultList->next = (struct ListNode *)malloc(sizeof(struct ListNode));
        }
            
    }
    return resultHead;
    }

Log in to reply
 

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