#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next=NULL;
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int minLen=0;
ListNode *a=l1,*b=l2;
ListNode *longOne,*shortOne;
bool isA=false;
while(1){
if(a==NULL){
cout<<"找到最短为a"<<endl;
shortOne=l1;
longOne=l2;
isA=true;
break;
}
if(b==NULL){
cout<<"找到最短为b"<<endl;
shortOne=l2;
longOne=l1;
isA=false;
break;
}
minLen++;
a=a->next;
b=b->next;
}
a=longOne;
cout<<"最短长度为 "<<minLen<<",最短链表是 "<<isA<<endl;
int carry=0;
while(shortOne!=NULL&&longOne!=NULL){
int sum=longOne->val+shortOne->val;
cout<<"将 "<<longOne->val<<" 和 "<<shortOne->val<<" 相加,得到"<<sum<<endl;
if(sum>=9&&carry==1||sum>=10){
longOne->val=sum-10+carry;
cout<<"产生进位,装入"<<sum-10+carry<<endl;
carry=1;
}else{
if(carry==1){
longOne->val=sum+1;
carry=0;
cout<<"使用掉进位,装入"<<sum+1<<endl;
}else{
longOne->val=sum;
cout<<"直接装入"<<sum<<endl;
}
}
if(carry==1&&longOne->next==NULL){
ListNode *node=new ListNode;
node->val=0;
longOne->next=node;
cout<<"长链表快没有了,续一个"<<endl;
}
longOne=longOne->next;
shortOne=shortOne->next;
}
while(longOne!=NULL){
if(carry==1){
int sum=longOne->val+1;
if(sum>=10){
longOne->val=sum-10;
cout<<"短链表没有了,但是有进位,装入"<<sum-10<<endl;
}else{
longOne->val=sum;
carry=0;
cout<<"短链表没有了,而且没有进位,装入"<<sum<<endl;
}
}else{
break;
}
if(longOne->next==NULL&&carry==1){
ListNode *node=new ListNode;
node->val=0;
longOne->next=node;
cout<<"长链表后面没有了,但是还有进位,续一个节点"<<endl;
}
longOne=longOne->next;
}
return a;
}
};
int main(){
ListNode a1,a2,a3,a4,a5,a6,a7,a8,a9,a10;
a1.val=1;
a2.val=9;
a3.val=9;
a4.val=9;
a5.val=9;
a6.val=9;
a7.val=9;
a8.val=9;
a9.val=9;
a10.val=9;
a1.next=&a2;
a2.next=&a3;
a3.next=&a4;
a4.next=&a5;
a5.next=&a6;
a6.next=&a7;
a7.next=&a8;
a8.next=&a9;
a9.next=&a10;
ListNode b1,b2,b3,b4;
b1.val=9;
b2.val=9;
b3.val=9;
b4.val=9;
// b1.next=&b2;
// b2.next=&b3;
// b3.next=&b4;
Solution s;
ListNode* re=s.addTwoNumbers(&b1,&a1);
while(re!=NULL){
cout<<re->val<<" ";
re=re->next;
}
return 0;
}
运行代码有输出可以看清运算过程。