C++ recursive solution


  • 0
    V

    class Solution
    {

    public:

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        return help(l1, l2, 0);
    }
    
    ListNode* help(ListNode* l1, ListNode* l2, int add)
    {
        if(l1 == nullptr && l2 == nullptr)
            if(add)
            {
                ListNode* node = new ListNode(add);
                return node;
            }
            else
                return nullptr;
        else
        {
            int sum = add;
            if(l1!=nullptr)
                sum+=l1->val;
            if(l2!=nullptr)
                sum+=l2->val;
            add = sum/10;
            sum = sum%10;
            ListNode* node = new ListNode(sum);
            node->next = help(l1!=nullptr?l1->next:nullptr, l2!=nullptr?l2->next:nullptr, add);
            return node;
        }
    }
    

    };


Log in to reply
 

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