
力扣 445.两数相加II C语言版题解
将链表中的数先储存在数组里,从个位开始对齐,不足的用0补齐。总共三种情况(len1>len2、len1
如样例1:
7 2 4 3
0 5 6 4
然后从个位数开始求和(sum),一位一位加,定义一个变量cnt,如果大于10,sum%=10,并且cnt=1。下一次循环判断cnt(cnt>0就加1)。
代码中有注释。
大一小白请大佬指点!
struct ListNode* addTwonumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head1=l1;
struct ListNode* head2=l2;
struct ListNode* head11=l1;
struct ListNode* head22=l2;
struct ListNode* head10=l1;
struct ListNode* head20=l2;
int m[102]={0};
int n[102]={0};
int len1=0;
int len2=0;
//获取链表总长
while (head1) {
len1++;
head1=head1->next;
}
while (head2) {
len2++;
head2=head2->next;
}
int c=len1-len2;
//c有三种情况
if(c>0) {
for(int i=0;ival;
head11=head11->next;
}
//更短的链表从c开始赋值,保证个位数对齐
for(int i=c;ival;
head22=head22->next;
}
//最开始不需要进位,cnt=0;
int cnt=0;
//从数组最后往前求和
for(int i=len1-1;i>=0;i--) {
int sum=m[i]+n[i];
if(cnt>0) {
sum+=cnt;//加完之后cnt重新回到0
cnt=0;
}
if(sum>=10) {
cnt=1;
sum%=10;
m[i]=sum;
}
else {
m[i]=sum;
}
}
// 求完和之后赋值到链表中
for(int i=0;ival=m[i];
head10=head10->next;
}
//此处cnt>0表示当i=0时向前进了一位,在前面加一个1
if(cnt>0) {
l2->val=1;
l2->next=l1;
return l2;
}
else {
return l1;
}
}
else{
if(c<0) {
c=-c;
for(int i=0;ival;
head22=head22->next;
}
for(int i=c;ival;
head11=head11->next;
}
int cnt=0;
for(int i=len2-1;i>=0;i--) {
int sum=m[i]+n[i];
if(cnt>0) {
sum+=cnt;
cnt=0;
}
if(sum>=10) {
cnt=1;
sum%=10;
m[i]=sum;
}
else {
m[i]=sum;
}
}
for(int i=0;ival=m[i];
head20=head20->next;
}
if(cnt>0) {
l1->val=1;
l1->next=l2;
return l1;
}
else {
return l2;
}
}
else {
for(int i=0;ival;
n[i]=head22->val;
head11=head11->next;
head22=head22->next;
}
int cnt=0;
for (int i=len1-1;i>=0;i--) {
int sum=m[i]+n[i];
if(cnt>0) {
sum+=1;
cnt=0;
}
if(sum>=10) {
cnt=1;
sum%=10;
m[i]=sum;
}
else {
m[i]=sum;
}
}
for(int i=0;ival=m[i];
head10=head10->next;
}
if(cnt>0) {
l2->val=1;
l2->next=l1;
return l2;
}
else {
return l1;
}
}
}
return NULL;
}
```
评论列表(0条)