You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int sum,k;
struct ListNode *l,*tmp,*ll;
l = NULL;
k = 0;
while(l1 && l2)
{
tmp = (struct ListNode *)malloc(sizeof(struct ListNode *));
sum = l1->val + l2->val+k;
tmp->val = sum%10;
tmp->next = NULL;
k = sum/10;
l1 = l1->next;
l2 = l2->next;
if(!l)
{
l=tmp;
ll=l;
}
else
{
ll->next = tmp;
ll=ll->next;
}
}
if(!l1 && l2)
{
while(l2)
{
tmp = (struct ListNode *)malloc(sizeof(struct ListNode *));
sum = l2->val+k;
tmp->val = sum%10;
tmp->next = NULL;
k = sum/10;
l2 = l2->next;
if(!l)
{
l=tmp;
ll=l;
}
else
{
ll->next = tmp;
ll=ll->next;
}
}
}
if(l1 && !l2)
{
while(l1)
{
tmp = (struct ListNode *)malloc(sizeof(struct ListNode *));
sum = l1->val+k;
k=0;
tmp->val = sum%10;
tmp->next = NULL;
k = sum/10;
l1 = l1->next;
if(!l)
{
l=tmp;
ll=l;
}
else
{
ll->next = tmp;
ll=ll->next;
}
}
}
if(k == 1)
{
tmp = (struct ListNode *)malloc(sizeof(struct ListNode *));
tmp->val = 1;
tmp->next = NULL;
ll->next = tmp;
}
return l;
}
链表不等长和进位问题!