Leetcode 445. Add Two Numbers II

文章作者: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/
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容