0445.cpp (1074B)
1 class Solution { 2 public: 3 pair<ListNode *, int> reverse(ListNode *root) { 4 ListNode *l = nullptr, *c = root; 5 int size = 0; 6 while (c) { 7 ListNode *n = c->next; 8 c->next = l; 9 l = c; 10 c = n; 11 size++; 12 } 13 return {l, size}; 14 } 15 16 ListNode *addTwoNumbers(ListNode *p1, ListNode *p2) { 17 auto [l1, s1] = reverse(p1); 18 auto [l2, s2] = reverse(p2); 19 20 if (s2 > s1) swap(l1, l2); 21 p1 = l1; 22 23 int carry = 0; 24 for (; l1 && l2; l1 = l1->next, l2 = l2->next) { 25 int sum = l1->val + l2->val + carry; 26 l1->val = sum % 10; 27 carry = sum / 10; 28 } 29 30 if (l1) { 31 while (true) { 32 int sum = l1->val + carry; 33 l1->val = sum % 10; 34 carry = sum / 10; 35 if (!l1->next) break; 36 l1 = l1->next; 37 } 38 } 39 40 if (!carry) return reverse(p1).first; 41 return new ListNode(carry, reverse(p1).first); 42 } 43 };