給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設除了數字 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 *head = (struct ListNode*)malloc(sizeof(struct ListNode)), *tail = head;
int carry = 0;
for (; l1 && l2; l1 = l1->next, l2 = l2->next){
int sum = l1->val + l2->val + carry;
if (sum > 9){
sum -= 10;
carry = 1;
}
else{
carry = 0;
}
tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = tail->next;
tail->val = sum;
}
l1 = l1 ? l1 : l2;
for( ; l1; l1 = l1->next){
int sum = l1->val + carry;
if (sum > 9){
sum -= 10;
carry = 1;
}
else {
carry = 0;
}
tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = tail->next;
tail->val = sum;
}
if (carry){
tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = tail->next;
tail->val = 1;
} tail->next = NULL;
tail = head;
head = head->next;
free(tail);
return head;
}