美文网首页Leetcode
Leetcode 445. Add Two Numbers II

Leetcode 445. Add Two Numbers II

作者: SnailTyan | 来源:发表于2018-10-08 18:54 被阅读2次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Add Two Numbers II

    2. Solution

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

    Reference

    1. https://leetcode.com/problems/add-two-numbers-ii/description/

    相关文章

      网友评论

        本文标题:Leetcode 445. Add Two Numbers II

        本文链接:https://www.haomeiwen.com/subject/plwjaftx.html