A common c++ solution


  • 0
    D
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* dummy = new ListNode(0);
            ListNode* ptr = dummy;
            int carry = 0;
            while (l1 != NULL || l2 != NULL || carry != 0) {
                int num_1 = l1 == NULL ? 0 : l1->val;
                int num_2 = l2 == NULL ? 0 : l2->val;
                int total = num_1 + num_2 + carry;
                carry = total >= 10 ? 1 : 0;
                total %= 10;
                ptr->next = new ListNode(total);
                ptr = ptr->next;
                if (l1 != NULL) l1 = l1->next;
                if (l2 != NULL) l2 = l2->next;
            }
            return dummy->next;
        }
    };
    

Log in to reply
 

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