leetcode 之Single Number(14)
这题并不难,但需要注意细节。
ListNode* addTwo(ListNode *l1, ListNode *l2) { ListNode dummy(-1); int carry = 0; ListNode *prev = &dummy; for (ListNode *pa = l1, *pb = l2; pa != nullptr || pb != nullptr; pa = pa == nullptr ? nullptr : pb->next, pb = pb == nullptr ? nullptr : pb->next,prev=prev->next) { int ai = pa == nullptr ? 0 : pa->val; int bi = pb == nullptr ? 0 : pb->val; int value = (ai + bi + carry) % 10; carry = (ai + bi + carry) / 10; prev->next = new ListNode(carry); } if (carry > 0) prev->next = new ListNode(carry); return dummy.next; }