给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 输出: 7 -> 8 -> 0 -> 7
这道题跟第二题类似,但是没有倒置链表,所以可以用栈去倒置。将各节点的元素依次压入栈,在计算的时候在pop,要注意的地方就是如果头节点的元素相加进位的情况,所以最后要有一个判断。
还有链表尾节点置为空,我坑了好几次。。。
#include<iostream>
#include<stack>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
class Solution{
public:
ListNode *addTwoNumbers(ListNode* l1,ListNode* l2)
{
stack<int> stackL1;
stack<int> stackL2;
while(l1){
stackL1.push(l1->val);
l1=l1->next;
}
while(l2){
stackL2.push(l2->val);
l2=l2->next;
}
ListNode* head=NULL;
int sum=0;
while(!stackL1.empty()||!stackL2.empty()){
sum/=10;
if(!stackL1.empty()){
sum+=stackL1.top();
stackL1.pop();
}
if(!stackL2.empty()){
sum+=stackL2.top();
stackL2.pop();
}
ListNode* node=new ListNode(sum%10);
node->next=head;
head=node;
}
//这个时判断链表都是空的了,但是还有进位的时候进行的运算
if(sum>=10){
ListNode* node=new ListNode(1);
node->next=head;
head=node;
/* head->next=node;
head=node;
node->next=NULL;*/
}
return head;
}
};
int main(){
int n,m,j,k;
ListNode* l1=(ListNode*)malloc(sizeof(ListNode)),*l2=(ListNode*)malloc(sizeof(ListNode)),*p=(ListNode*)malloc(sizeof(ListNode));
ListNode* head1=l1;
ListNode* head2=l2;
cin>>n;
for(int i=0;i<n;i++){
cin>>j;
ListNode *t=(ListNode*)malloc(sizeof(ListNode));
t->val=j;
t->next=NULL;
l1->next=t;
l1=t;
}
cin>>m;
for(int i=0;i<m;i++){
cin>>k;
ListNode *t=(ListNode*)malloc(sizeof(ListNode));;
t->val=k;
t->next=NULL;
l2->next=t;
l2=t;
}
Solution solution;
p=solution.addTwoNumbers(head1->next,head2->next);
while(p){
cout<<p->val<<" ";
p=p->next;
}
system("pause");
}