题目链接 https://leetcode.com/problems/add-two-numbers/
题目描述
给你两个非空链表代表两个非负整数,其中数字的每一位数字按照逆序存储在链表的每一个结点中,将这两个数相加并返回同样的一个链表。
你可以假设两个数字均不会以0开头,除了0本身。
样例
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
代码
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int len1=0,len2=0;
int x=0;
struct ListNode *res = NULL,*next = NULL,*head;
while(l1||l2)
{
if(l1&&l2)
{
if(!res)
{
res = malloc(sizeof(struct ListNode));
res->val = l1->val+l2->val;
res->next = NULL;
head = res;
if(res->val>9)
{
res->val = res->val - 10;
x = 1;
}
}
else
{
next = malloc(sizeof(struct ListNode));
next->val = l1->val + l2->val + x;
next->next = NULL;
x=0;
if(next->val > 9)
{
next->val -= 10;
x = 1;
}
res->next = next;
res = res->next;
}
l1=l1->next;
l2=l2->next;
}
else if(l1)
{
next = malloc(sizeof(struct ListNode));
next->val = l1->val + x;
next->next = NULL;
x=0;
if(next->val > 9)
{
next->val -= 10;
x = 1;
}
res->next = next;
res = res->next;
l1=l1->next;
}
else if(l2)
{
next = malloc(sizeof(struct ListNode));
next->val = l2->val + x;
next->next = NULL;
x=0;
if(next->val > 9)
{
next->val -= 10;
x = 1;
}
res->next = next;
res = res->next;
l2=l2->next;
}
}
if(x == 1)
{
next = malloc(sizeof(struct ListNode));
next->val = 1;
next->next = NULL;
res->next = next;
}
return head;
}