C++ 36ms without extra space, with comments


  • 1
    E
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* cur1 = l1;
        ListNode* cur2 = l2;
        int len1 = 0, len2 = 0;
        while (cur1) {
            cur1 = cur1->next;
            len1++;
        }
        while (cur2) {
            cur2 = cur2->next;
            len2++;
        }
    
        // come up with the length of two lists and take the longer one as l1.
    
        if (len1 < len2)
            return addTwoNumbers(l2, l1);
        cur1 = l1;
        cur2 = l2;
        bool carry = false;
    
        // if carry is true in the end, need one node(1) in the end of the list
    
        ListNode* prenode1; 
        while (cur1 && cur2) {
            cur1->val += cur2->val;
            if (carry) {
                cur1->val += 1;
                carry = false;
            }
            if (cur1->val >= 10) {
                cur1->val -= 10;
                carry = true;
            }
            prenode1 = cur1;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        while (cur1 && carry) {
            cur1->val += 1;
            carry = false;
            if (cur1->val >= 10) {
                cur1->val -= 10;
                carry = true;
            }
            prenode1 = cur1;
            cur1 = cur1->next;
        }
        if (carry) {
            ListNode* newnode = new ListNode(1);
            prenode1->next = newnode;
            return l1;
        }
        return l1;
    }

Log in to reply
 

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