You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* l3,*l4;
int carry=0;//进位位;
int a,b;//储存加数和被加数
int sum;//对应位与进位相加和
l3=(struct ListNode*)malloc(sizeof(struct ListNode));
l4=l3;//储存首元结点的值
while(l1!=NULL||l2!=NULL)
{
a=(l1==NULL)?0:l1->val;
b=(l2==NULL)?0:l2->val;
sum=a+b+carry;
carry=sum/10;
l3->next=(struct ListNode*)malloc(sizeof(struct ListNode));
l3=l3->next;
l3->val=sum%10;
l1=(l1!=NULL)?l1->next:l1;
l2=(l2!=NULL)?l2->next:l2;
}
if(carry==1)
{
l3->next=(struct ListNode*)malloc(sizeof(struct ListNode));
l3=l3->next;
l3->val=1;
}
l3->next=NULL;
return l4->next;
}