C++ recursion


  • 0
    A
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            return addTwoNumbers(l1, l2, 0);
        }
    private:
        ListNode* addTwoNumbers(ListNode* a, ListNode* b, int c) {
            if (a == nullptr && b == nullptr && c == 0) {
                return nullptr;
            }
    
            if (a != nullptr) {
                c += a->val;
                a = a->next;
            } 
            if (b != nullptr) {
                c += b->val;
                b = b->next;
            } 
            
            ListNode* node = new ListNode(c % 10);
            node->next = addTwoNumbers(a, b, c / 10);
    
            return node;
        }
    };
    

Log in to reply
 

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