题目:
分析:
使用起来很方便。
代码:
#include<bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int main()
{
ListNode* l1;
stack<int> s1;
ListNode* l2;
stack<int> s2;
if(l1==NULL) return l2;
if(l2==NULL) return l1;
while(l1!=NULL)
{
s1.push(l1->val);
l1=l1->next;
}
while(l2!=NULL)
{
s2.push(l2->val);
l2=l2->next;
}
stack<int> s;
int cc=0;//进位
while(s1.size()!=0||s2.size()!=0)
{
int c=0;
if(!s1.empty())
{
c+=s1.top();s1.pop();
}
if(!s2.empty())
{
c+=s2.top();s2.pop();
}
c+=cc;
if(c>=10)
{
cc=1;c=c%10;
}
else cc=0;
s.push(c);
}
if(cc!=0) s.push(1);
ListNode* l=new ListNode(s.top());
s.pop();
ListNode* ll=l;
while(!s.empty())
{
ListNode* ll->next=new ListNode(s.top());
s.pop();
ll=ll->next;
}
return l;
}