C++ solution 29ms


  • 0
    S
        ListNode* addTwoNumbers(ListNode* list1, ListNode* list2) {
            if (!list1 || !list2) {
                return (list1) ? list1:list2;
            }
            ListNode * it1 = list1;
            ListNode * it2 = list2;
            ListNode * ret_list;
            ListNode * it_ret;
            ListNode * new_node;
            int carry;
            int sum = it1->val + it2->val;
            if (sum >= 10) {
                sum = sum % 10;
                carry = 1;
            } else {
                carry = 0;
            }
            new_node = new ListNode(sum);
            ret_list = new_node;
            it_ret = new_node;
            it1 = it1->next;
            it2 = it2->next;
            
            int it1_val;
            int it2_val;
            while (true) {
                if (!it1 && !it2) {
                    if (carry) {
                        new_node = new ListNode(1);
                        it_ret->next = new_node;
                    }
                    return ret_list;
                }
                it1_val = (it1) ? it1->val : 0;
                it2_val = (it2) ? it2->val : 0;
                sum = it1_val + it2_val + carry;
                if (sum >= 10) {
                    sum = sum % 10;
                    carry = 1;
                } else {
                    carry = 0;
                }
                new_node = new ListNode(sum);
                it_ret->next = new_node;
                it_ret = new_node;
                if (it1) {
                    it1 = it1->next;
                }
                if (it2) {
                    it2 = it2->next;
                }
            }
        }
    

Log in to reply
 

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