原題鏈接:https://leetcode-cn.com/problems/add-two-numbers-ii/
棧
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> s1;//存儲l1
stack<int> s2;//存儲l2
while(l1!=NULL){
s1.push(l1->val);
l1=l1->next;
}
while(l2!=NULL){
s2.push(l2->val);
l2=l2->next;
}
int a,b,c=0;
ListNode *head=new ListNode(0);
while(!s1.empty()||!s2.empty()){
if(!s1.empty()){
a=s1.top();
s1.pop();
}else{
a=0;
}
if(!s2.empty()){
b=s2.top();
s2.pop();
}else{
b=0;
}
int x=(a+b+c)%10;
c=(a+b+c)/10;
ListNode *tmp=new ListNode;
tmp->val=x;
tmp->next=head->next;
head->next=tmp;
}
if(c!=0){
head->val=c;
return head;
}
return head->next;
}