16ms C solution.


  • -1
    J
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        if (!l1) {
            return l2;
        } else if (!l2) {
            return l1;
        }
    
        struct ListNode *answer_head = NULL, *answer_tail = NULL,
                        *node1 = l1, *node2 = l2;
    
        int carry = 0;
        while (1) {
            int temp1 = 0;
            if (node1) {
                temp1 = node1->val;
            }
    
            int temp2 = 0;
            if (node2) {
                temp2 = node2->val;
            }
    
            if (node1 || node2 || carry != 0) {
                if (node1) {
                    node1 = node1->next;
                }
                if (node2) {
                    node2 = node2->next;
                }
            
                if (!answer_head) {
                    answer_head =
                        (struct ListNode*) malloc(sizeof(struct ListNode));
     	            answer_head->next = NULL;
                    answer_tail = answer_head;
                } else {
                    answer_tail->next =
                        (struct ListNode*) malloc(sizeof(struct ListNode));
                    answer_tail = answer_tail->next;
    	            answer_tail->next = NULL;
                }
                int sum = temp1 + temp2 + carry;
                answer_tail->val = sum % 10;
                carry = sum / 10;
            } else {
                answer_tail->next = NULL;
                return answer_head;
            }
        }
    
        // Should not get here.
        return answer_head; 
    }

Log in to reply
 

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