C++ concise solution.


  • 9
    C
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode *dummy = new ListNode(0), *cur;
        cur = dummy;
        while (l1 || l2 || carry) {
            if (l1) {
                carry += l1->val;
                l1 = l1->next;
            }
            if (l2) {
                carry += l2->val;
                l2 = l2->next;
            }
            cur->next = new ListNode(carry%10);
            cur = cur->next;
            carry /= 10;
        }
        return dummy->next;
    }

  • 0
    L

    This solution has memory leak problem. You can change

    ListNode *dummy = new ListNode(0), *cur;
    curr = dummy;
    ...
    return dummy->next;
    

    to

    ListNode dummy(0);
    ListNode *curr = &dummy;
    ...
    return dummy.next;
    

Log in to reply
 

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