Simple C++ Recursive Solution without using extra memory


#1
ListNode *addTwo(ListNode* A, ListNode* B, int carry = 0){
    if(A == nullptr && B==nullptr){
        if(carry)
            return new ListNode(carry);
        return nullptr;
    }
    auto h = A && B?A:nullptr;
    if(h)
        h->val += B->val;
    else
        h = A == nullptr?B:A;
    h->val += carry;
    carry = h->val/10;
    h->val = h->val%10;
    h->next = addTwo(A==nullptr?A:A->next, B== nullptr?B:B->next, carry);
    return h;
}

ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
    if(A == nullptr && B==nullptr)
        return nullptr;
    return addTwo(A, B);
}