两数相加 Add Two Numbers
题目:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因: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 *p=l1;
struct ListNode *q=l2;
int carry=0; //进位标志
struct ListNode *list =(struct ListNode*)malloc(sizeof(struct ListNode)) ;
struct ListNode *sum=list;
while(p!=NULL||q!=NULL||carry){
sum->next = (struct ListNode*)malloc(sizeof(struct ListNode));
sum=sum->next;
if(p!=NULL&&q!=NULL){
sum->val = p->val+q->val+carry;
p=p->next;
q=q->next;
}else if (p!=NULL&&q==NULL){
sum->val=p->val+carry;
p=p->next;
}else if (q!=NULL&&p==NULL){
sum->val=q->val+carry;
q=q->next;
}else{
sum->val=carry;
}
carry=sum->val/10; //最后一位有进位的情况
sum->val=sum->val%10; //无论是否有进位都取一位
}
sum->next =NULL;
return list->next;
}