1. 程式人生 > >Leetcode 445. Add Two Numbers II

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