參考資訊:
https://www.cnblogs.com/grandyang/p/4129891.html
題目:
解答:
struct ListNode* addTwoNumbers(struct ListNode *l1, struct ListNode *l2) { int carry = 0; struct ListNode *r = malloc(sizeof(struct ListNode)); struct ListNode *cur = r; r->val = 0; r->next = NULL; while (l1 || l2) { int v1 = l1 ? l1->val : 0; int v2 = l2 ? l2->val : 0; int sum = v1 + v2 + carry; carry = sum / 10; cur->next = malloc(sizeof(struct ListNode)); cur->next->val = sum % 10; cur->next->next = NULL; cur = cur->next; if (l1) { l1 = l1->next; } if (l2) { l2 = l2->next; } } if (carry) { cur->next = malloc(sizeof(struct ListNode)); cur->next->val = 1; cur->next->next = NULL; } return r->next; }