题目描述:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807
示例2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示
- 每个链表中的节点数在范围
[1, 100]
内 0 <= Node.val <= 9
- 题目数据保证列表表示的数字不含前导零
代码示例:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int carry = 0;
struct ListNode* head = NULL, *tail = NULL;
while(l1 && l2) {
if(tail == NULL) {
tail = (struct ListNode*)malloc(sizeof(struct ListNode));
head = tail;
} else {
tail -> next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = tail -> next;
}
tail -> val = (l1 -> val + l2 -> val + carry) % 10;
carry = (l1 -> val + l2 -> val + carry) / 10;
tail -> next = NULL;
l1 = l1 -> next;
l2 = l2 -> next;
}
while(l1) {
if(tail == NULL) {
tail = (struct ListNode*)malloc(sizeof(struct ListNode));
head = tail;
} else {
tail -> next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = tail -> next;
}
tail -> val = (l1 -> val + carry) % 10;
carry = (l1 -> val + carry) / 10;
tail -> next = NULL;
l1 = l1 -> next;
}
while(l2) {
if(tail == NULL) {
tail = (struct ListNode*)malloc(sizeof(struct ListNode));
head = tail;
} else {
tail -> next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = tail -> next;
}
tail -> val = (l2 -> val + carry) % 10;
carry = (l2 -> val + carry) / 10;
tail -> next = NULL;
l2 = l2 -> next;
}
if(carry) {
tail -> next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = tail -> next;
tail -> val = carry;
tail -> next = NULL;
}
return head;
}