原题链接:Add two numbers II
题解:
//分析:这道题是Add two numbers的演化版,当然可以先将链表反转,然后回到了之前的那道题。但是题目明确follow not modify the input lists,就是禁止反转输入链表。怎么办呢?链表从高位到低位,加法从低位到高位,貌似这种关系可以借用到栈的先进后出嚎~。于是答案就来了:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <stack>
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
/*
Time Complexity:O(max(n,m))
Space Complexity:O(m+n)
*/
if(!l1)return l2;
if(!l2)return l1;
stack<int>s1;
stack<int>s2;
while(l1){
s1.push(l1->val);
l1=l1->next;
}
while(l2){
s2.push(l2->val);
l2=l2->next;
}
int flag=0;
int temp=0;
ListNode* res=NULL;
while(!s1.empty() && !s2.empty()){
temp=s1.top()+s2.top()+flag;
s1.pop();
s2.pop();
flag=temp/10;
ListNode* ptr=new ListNode(temp%10);
ptr->next=res;
res=ptr;
}
while(!s1.empty()){
temp=s1.top()+flag;
s1.pop();
flag=temp/10;
ListNode* ptr=new ListNode(temp%10);
ptr->next=res;
res=ptr;
}
while(!s2.empty()){
temp=s2.top()+flag;
s2.pop();
flag=temp/10;
ListNode* ptr=new ListNode(temp%10);
ptr->next=res;
res=ptr;
}
if(flag){
ListNode* ptr=new ListNode(1);
ptr->next=res;
res=ptr;
}
return res;
}
};