1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *head = nullptr, *tail = nullptr; int carry_bit = 0; while (l1 || l2) { int number1 = 0, number2 = 0, sum = 0; if (l1) number1 = l1->val; if (l2) number2 = l2->val; sum = number1 +number2+ carry_bit; if (!head) head = tail = new ListNode(sum % 10); else { tail->next = new ListNode(sum % 10); tail = tail->next; } carry_bit = sum/10; if(l1) l1 = l1->next; if(l2) l2 = l2->next; } if (carry_bit==1) { tail->next = new ListNode(1); tail = tail->next; } return head; } };
|