A 20ms C Solution


  • 0
    D

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)   {
        if(NULL == l1 || NULL == l2) {
            return (NULL == l1) ? l2 : l1;
        }
    
        struct ListNode* result = NULL;
    	struct ListNode* head = NULL;
    
    	int sum = 0;
    	while(l1 != NULL || l2 != NULL || sum == 1){
    		int val = ((l1 == NULL) ? 0 : l1->val) + ((l2 == NULL) ? 0 : l2->val)+sum;
    		struct ListNode* tm = (struct ListNode*) malloc(sizeof(struct ListNode));
    		tm->next = NULL;
    		if(val >= 10){
    			tm->val = val % 10;
    			sum = 1;
    		}else{
    			tm->val = val;
    			sum = 0;
    		}
    		
    		
    		if(head == NULL){
    			head = tm;
    		}else{
    			result->next = tm;
    		}
    		result = tm;
    
    		if(l1 != NULL)l1 = l1->next;
    		if(l2 != NULL)l2 = l2->next;
    	}
    	return head;
    }
    

Log in to reply
 

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