Help!c,this case {[0],[0]} Runtime Error!


  • 0
    H

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

    struct ListNode ans[2048];
    int sum=0,subsum,cin=0,i,n=0;
    
    struct ListNode * num1;
    struct ListNode * num2;
    
    num1 = l1;
    num2 = l2;
    do
    {   
        
        
        if(num1!=NULL&&num2!=NULL)
            subsum = num1->val + num2->val + cin;
        else if(num1!=NULL)
            subsum = num1->val + cin;
        else if(num2!=NULL)
            subsum = num2->val + cin;
        else 
            subsum = cin;
            
        cin = subsum/10;
    	//printf("%d\n",subsum);
    	sum=sum*10+subsum%10;
        
    	n=n+1;
        
        if(num1!=NULL) num1 = num1->next;
        //else num1 = NULL;
        if(num2!=NULL) num2 = num2->next;
        //else num2 = NULL;
    }while(num1!=NULL||num2!=NULL||cin!=0);
    
    //printf("%d,%d",sum,n);
    
    for(i=0;i<n;i++) {
    	
    
    	ans[i].val = sum%10;
    	if(i==0)
    		ans[i].next = NULL;
    	else
    		ans[i].next = &ans[i-1];
    	sum=sum/10;
    
    	}
    
    
    return &ans[n-1];
    

    }

    what's wrong with my code???


  • 0
    K

    You have couple of problems in your code.
    First, you are returning a single node at n-1. You need return a list not a node. To return a list, it should be like this:

    return &ans;
    

    Also, since you know the length of the answer, you can just declare list with the length.

    Second, the way you do "sum" thing, it adds values in backward in ans list. Because you add value using mod 10 it add value from right side. You can for loop from n-1 to 0 to solve this.

    I recommend you to take advantages of linked list since you are not taking any of them.


Log in to reply
 

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