Clean C++ solution 47ms


  • 9
    R
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode node(0);
        ListNode* p1 = l1;
        ListNode* p2 = l2;
        ListNode* parent =&node;
        int more = 0;
        
        while (p1 || p2 || more) {
            int d1 = p1 ? p1->val : 0;
            int d2 = p2 ? p2->val : 0;
            if (p1) p1 = p1->next;
            if (p2) p2 = p2->next;
            more += d1 + d2;
            ListNode* node = new ListNode(more % 10);
            parent->next = node;
            parent = node;
            more /= 10;
        }
        
        return node.next;
    }

Log in to reply
 

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