Problem:
给定两个代表两个非负整数的非空链表。这些数字以相反的顺序存储,并且它们的每个节点都包含一个数字。将两个数字相加并将总和作为链表返回。您可以假设这两个数字不包含任何前导零,除了数字 0 本身。
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int rem = 0;
struct ListNode* head = NULL;
struct ListNode* parent = NULL;
do {
int n = rem;
if (l1 != NULL) {
n += l1->val;
}
if (l2 != NULL) {
n += l2->val;
}
rem = n / 10;
n = n % 10;
struct ListNode* child = (struct ListNode*)malloc(sizeof(struct ListNode));
child->val = n;
child->next = NULL;
if (parent == NULL) {
head = child;
} else {
parent->next = child;
}
parent = child;
if (l1 != NULL) {
l1 = l1->next;
}
if (l2 != NULL) {
l2 = l2->next;
}
} while (l1 != NULL || l2 != NULL);
if (rem > 0) {
parent->next = (struct ListNode*)malloc(sizeof(struct ListNode));
parent->next->val = rem;
parent->next->next = NULL;
}
return head;
}