https://leetcode.com/problems/add-two-numbers-ii/description/
Linked List + Stack;
最后的操作有点tricky
/**
* 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;
while(l1){
s1.push(l1->val);
l1 = l1->next;
}
while(l2){
s2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
ListNode *res = new ListNode(0);
while(!s1.empty() || !s2.empty() || carry != 0){
if(!s1.empty()){
carry = carry + s1.top();
s1.pop();
}
if(!s2.empty()){
carry = carry + s2.top();
s2.pop();
}
ListNode *head = new ListNode(carry%10);
head->next = res->next;
res->next = head;
carry /= 10;
}
return res->next;
}
};