12 lines recursive C++


  • 1
    V
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            return add2(l1, l2, 0);
            
        }
        ListNode* add2(ListNode* l1, ListNode* l2, int c) {
            if (!l1 && !l2) {
                ListNode *lastNode = NULL;
                if (c)
                    lastNode = new ListNode(c);
                return lastNode;
            }
            else {
                int val = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + c;
                ListNode *newNode = new ListNode(val % 10);
                newNode->next = add2(l1 ? l1->next : NULL, l2 ? l2->next : NULL, val / 10);
                return newNode;
            }
        }
    

Log in to reply
 

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