给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 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;
struct ListNode* sum = NULL; //和
struct ListNode* last = NULL;//指向sum的最后一个节点
int carry = 0;
while (p != NULL && q != NULL)
{
int s = p->val + q->val + carry;
carry = 0;
if (s > 9){
s -= 10;
carry = 1;
}
if (!sum){
sum = (struct ListNode*)malloc(sizeof(struct ListNode));
sum->val = s;
sum->next = NULL;
last = sum;
}else{
struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
t->val = s;
t->next = last->next;
last->next = t;
last = t;
}
p = p->next;
q = q->next;
}
if (p){ //如果p有更高位
last->next = p;
}else if (q){ //如果q有更高位
last->next = q;
}
//如果还有一个进位,那么需要分为两种处理:第一,p和q长度相同,那么需要新建一个节点,存储最高进位
//第二:如果p和q不相同,那么该进位需要继续与多出来的位进行加法运算
if (carry){
while (last->next){
int s = carry + last->next->val;
carry = 0;
if (s > 9){
s -= 10;
carry = 1;
}
last->next->val = s;
if (carry){
last = last->next;
}else{
break;
}
}
if (!last->next){
struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
t->val = carry;
t->next = last->next;
last->next = t;
last = t;
}
}
return sum;
}