# 【leetcode】两数相加

输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)



/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
if(l1==NULL)
{
return l2;
}
if(l2==NULL)
{
return l1;
}
struct ListNode* head=(struct ListNode*)malloc(sizeof(struct ListNode));
int in=0;//进位标识，1表示有进位，0表示无进位

result->val=(l1->val+l2->val)%10;
in=(l1->val+l2->val)/10;
printf("in=%d\n",in);
l1=l1->next;
l2=l2->next;
while(l1!=NULL && l2!=NULL)
{
struct ListNode*tmp=(struct ListNode*)malloc(sizeof(struct ListNode));
int sum=l1->val+l2->val+in;
tmp->val=sum%10;
in=sum/10;
result->next=tmp;
result=result->next;

printf("l1=%d,l2=%d,result=%d,in=%d\n",l1->val,l2->val,result->val,in);

l1=l1->next;
l2=l2->next;
}
while(l1!=NULL)
{
struct ListNode*tmp=(struct ListNode*)malloc(sizeof(struct ListNode));
int sum=l1->val+in;
tmp->val=sum%10;
in=sum/10;
result->next=tmp;
result=result->next;

printf("l1=%d,result=%d,in=%d\n",l1->val,result->val,in);

l1=l1->next;
}
while(l2!=NULL)
{
struct ListNode*tmp=(struct ListNode*)malloc(sizeof(struct ListNode));
int sum=l2->val+in;
tmp->val=sum%10;
in=sum/10;
result->next=tmp;
result=result->next;

printf("l2=%d,result=%d,in=%d\n",l2->val,result->val,in);

l2=l2->next;
}
if(in==1)
{
printf("in==1\n");
struct ListNode*tmp=(struct ListNode*)malloc(sizeof(struct ListNode));
tmp->val=1;
result->next=tmp;
result=result->next;
}
result->next=NULL;
printf("result=%d\n",result->val);
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120