Add two numbers : Run time error


  • 0

    '''
    class Solution {
    public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *newNode, tmphead, previous;
    int tmp,val,carry=0;
    newNode=(ListNode
    ) malloc(sizeof(ListNode));
    tmphead=newNode;
    while(l1!=NULL || l2!=NULL){
    tmp=0;
    if (l1!=NULL){
    tmp=tmp+l1->val;
    l1=l1->next;
    }
    if (l2!=NULL){
    tmp=tmp+l2->val;
    l2=l2->next;
    }
    tmp=tmp+carry;
    carry=(int)tmp/10;
    tmphead->val=tmp%10;
    previous=tmphead;
    tmphead->next=(ListNode
    ) malloc(sizeof(ListNode));
    tmphead=tmphead->next;
    }

        if(carry==1){
            tmphead->val=1;
        }
        else{
            previous->next=NULL;
            free(tmphead);
        }
     return newNode;   
    }
    

    };

    '''

    Code is running fine on my machine, but gives a run-time error while submitting it. Any help is much appreciated.


  • 0
    E

    @mayank-garg333-gmail-com I think you should add a line like 'tmphead->next = NULL;' in the while.


Log in to reply
 

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