给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
}SN;
int a1[4]={9,9,9,9};
int a2[3]={1,0,0};
SN *CreateLink(int a[],int i)
{
SN *h=NULL,*p,*tail;
int j;
for(j=0;j<i;j++)
{
p=(SN *)malloc(sizeof(SN));
p->next=NULL;
p->val=a[j];
if(!h)h=tail=p;
else tail=tail->next=p;
}
return h;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int remainder=0,integer=0;
struct ListNode *head=NULL,*p,*tail=NULL,*l;
while(l1&&l2)
{
p=(struct ListNode *)malloc(sizeof(struct ListNode));
p->next=NULL;
integer=(l1->val+l2->val)%10;
p->val=(integer+remainder)%10;
remainder=(l1->val+l2->val)/10+(integer+remainder)/10;
l1=l1->next;
l2=l2->next;
if(!head)head=tail=p;
else tail=tail->next=p;
}
if(l1)l=l1;
else if(l2)l=l2;
while(l||remainder)
{
p=(struct ListNode *)malloc(sizeof(struct ListNode));
p->next=NULL;
if(l)
{
p->val=(l->val+remainder)%10;
remainder=(l->val+remainder)/10;
l=l->next;
tail=tail->next=p;
}
else {
p->val=remainder;
tail->next=p;
remainder=0;
}
}
return head;
}
int main()
{
SN *head1,*head2,*p,*h=NULL;
head1=CreateLink(a1,4);
head2=CreateLink(a2,3);
h=addTwoNumbers(head1,head2);
for(p=h;p;p=p->next)
printf("%d",p->val);
return 0;
}
第一次错误:忽略了两个数组长度相等时,如果在最后相加出现超9问题。
第二次错误:
解决办法:相加结束的标志应该是两个数组都扫描完和十分位为0。
最后