Why am i getting a runtime error?


  • 0
    W
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if(l1==NULL && l2!=NULL)
            return l2;
        if(l1!=NULL && l2==NULL)
            return l1;
        if(l1==NULL && l2==NULL)
            return NULL;
            ListNode* start=(ListNode*)malloc(sizeof(ListNode));
            ListNode* temp=start;
            int sum=0;
            int carry=0;
            while(l1!=NULL && l2!=NULL)
            {
                sum=(l1->val+l2->val+carry)%10;
                carry=(l1->val+l2->val+carry)/10;
                start->val=sum;
                start->next=(ListNode*)malloc(sizeof(ListNode));
                l1=l1->next;
                l2=l2->next;
                start=start->next;
            }
             while(l1!=NULL)
            {
                sum=(l1->val+carry)%10;
                carry=(l1->val+carry)/10;
                start->val=sum;
                start->next=(ListNode*)malloc(sizeof(ListNode));
                l1=l1->next;
                start=start->next;
            }
             while(l2!=NULL)
            {
                sum=(l2->val+carry)%10;
                carry=(l2->val+carry)/10;
                start->val=sum;
                start->next=(ListNode*)malloc(sizeof(ListNode));
                l2=l2->next;
                start=start->next;
            }
            if(carry!=0)
            {
                start->val=carry;
                start->next=NULL;
                return temp;
            }
            else
            {
                ListNode* t=temp;
                while(temp->next->next!=NULL)
                temp=temp->next;
                temp->next=NULL;
                return t;
            }
            
        }
    };

  • 0
    J

    ctrl+k when input code : )


  • 0
    K

    You are missing brackets in third if statement. Add that and see if it still gets error.


Log in to reply
 

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