My simple solution works well!


  • 0
    C
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* ans;
    	if(!l1||!l2) return ans;
    	ans = new ListNode(1);
    	ListNode* p1=l1,*p2=l2,*a=ans;
    	int nt = 0;
    	while(p1&&p2){
    		a->next = new ListNode(p1->val+p2->val+nt);
    		a = a->next;
    		nt = a->val/10;
    		a->val = a->val%10;
    		p1 = p1->next;
    		p2 = p2->next;
    		
    	}
    	ListNode *q = p1?p1:p2;
    	a->next = q;
    	while(nt&&a->next){
    		a->next->val = a->next->val+nt;
    		nt = a->next->val/10;
    		a->next->val = a->next->val%10;
    		a = a->next;
    	}
    	if(nt)
    		a->next = new ListNode(1);
    	 return ans->next;
    }

  • 0
    T

    You can return the first linked as the ans, though that's not conform to the standard.

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    		if(l1==NULL) return l2;
    		if(l2==NULL) return l1;
    
    		ListNode* newList = l1;
    		int c=0,sum=0;
    		while(l1!=NULL || l2!=NULL){
    			sum = l1->val + (l2?l2->val:0) + c;
    			l1->val = sum%10;
    			c = sum/10;
    			l2 = l2?l2->next:NULL;
    			if(!l1->next&&(c||l2)) l1->next = new ListNode(0);
    			l1 = l1->next;
    		}
    		return newList;
        }

Log in to reply
 

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