给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
/**
* 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) {
if(!l1){
return l2;
}
if(!l2){
return l1;
}
stack<int>s1,s2;
auto p1=l1;
auto p2=l2;
while(p1){
s1.push(p1->val);
p1=p1->next;
}
while(p2){
s2.push(p2->val);
p2=p2->next;
}
ListNode* temp=NULL;
int flag=0;
while(s1.size()||s2.size()||flag){
int x1,x2;
if(s1.size()==0)
x1=0;
else
x1=s1.top();
if(s2.size()==0)
x2=0;
else
x2=s2.top();
if(s1.size())
s1.pop();
if(s2.size())
s2.pop();
int num=(x1+x2+flag)%10;
flag=(x1+x2+flag)/10;
ListNode* pos=new ListNode (num);
pos->next=temp;
temp=pos;
}
return temp;
}
};