445. 两数相加

445. 两数相加 II - 力扣(LeetCode)

解法一:栈

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        stack<int> s1,s2;
        while (l1) {
            s1.push(l1->val);
            l1 =l1->next;
        }
        while(l2) {
            s2.push(l2->val);
            l2 = l2->next;
        }
        int carry =0;
        ListNode* ans = nullptr;
        while (!s1.empty() || (!s2.empty()) || carry!=0) {
            if (!s1.empty()) {
                carry += s1.top();
                s1.pop();
            }
            if (!s2.empty()) {
                carry += s2.top();
                s2.pop();
            }
            auto cur_node = new ListNode(carry%10);
            cur_node -> next =ans;
            ans = cur_node;
            carry = carry / 10;
        }
        return ans;
    }
};

解法二:dfs

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int diff = size(l1)-size(l2);
        l1 = new ListNode(0, l1);
        l2 = new ListNode(0, l2);
        if (diff<0) {
            fillZero(l1, -diff);
        } else {
            fillZero(l2, diff);
        }

        dfs(l1, l2);

        return l1->val==0?l1->next:l1;
    }

    int dfs(ListNode *l1, ListNode *l2) {
        if (l1==nullptr) {
            return 0;
        }

        int carry = dfs(l1->next, l2->next);

        int sum = l1->val+l2->val+carry;
        
        l1->val = sum % 10;
        carry = sum / 10;
        return carry;
    }
    int size(ListNode *l) {
        int size = 0;
        while (l != nullptr) {
            size++;
            l = l->next;
        }
        return size;
    }

    void fillZero(ListNode *l, int n) {
        while (n > 0) {
            n--;
            ListNode* cur = new ListNode();
            cur->next = l->next;
            l->next = cur;
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值