首页 > 代码库 > Add Two Numbers[leetcode]

Add Two Numbers[leetcode]

我写了两个版本供参考:

递归版本

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        return addTwoNumbers(l1, l2, 0);
    }
    
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2, int carry) {
        if(l1 == NULL)
            return addTwoNumbers(l2, carry);
        if(l2 == NULL)
            return addTwoNumbers(l1, carry);
        l1->val += (l2->val + carry);
        l1->next = addTwoNumbers(l1->next, l2->next, l1->val / 10);
        l1->val %= 10;
        return l1;
    }
    
    ListNode *addTwoNumbers(ListNode *l, int carry) {
        if(l == NULL)
            if (carry)
                return new ListNode(carry);
            else
                return NULL;
        l->val += carry;
        l->next = addTwoNumbers(l->next, l->val / 10);
        l->val %= 10;
        return l;
            
    }


非递归版本

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        ListNode* root = new ListNode(0);
        ListNode* cur = root;

        int carry = 0;
        do
        {
            cur->val = (l1 == NULL ? 0 : l1->val) + (l2 == NULL ? 0 : l2->val) + carry;
            carry = cur->val / 10;
            cur->val = cur->val % 10;
            l1 = (l1 == NULL ? NULL : l1->next);
            l2 = (l2 == NULL ? NULL : l2->next);
            if (!l1 && !l2) break;
            
            cur->next = new ListNode(0);
            cur = cur->next;
        }while (l1 || l2);
        
        if (carry)
            cur->next = new ListNode(carry);
        return root;
    }


Add Two Numbers[leetcode]