这儿的顺序与正常的相加不一样,使用栈倒腾一下就可以了。
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;
}
ListNode* head = NULL;
int x = 0;
while(!s1.empty() || !s2.empty() || x){
int a = s1.empty() ? 0 : s1.top();
int b = s2.empty() ? 0 : s2.top();
if (!s1.empty()) s1.pop();
if (!s2.empty()) s2.pop();
int cur = a + b + x;
x = cur / 10;
auto node = new ListNode(cur%10);
node->next = head;
head = node;
}
return head;
}
};