2. AddTwoNumbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
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 52 53 54 55 56 class Solution {private : ListNode* add (ListNode* l1, ListNode* l2, int val) { if (l2 == nullptr ) return new ListNode (l1->val + val); else return new ListNode (l1->val + l2->val + val); } public : ListNode* addTwoNumbers (ListNode* l1, ListNode* l2) { ListNode* solution = new ListNode; ListNode* cur = solution; int val = 0 ; while (l1 != nullptr && l2 != nullptr ) { cur->next = add (l1, l2, val); cur = cur->next; l1 = l1->next; l2 = l2->next; if (cur->val >= 10 ) { cur->val -= 10 ; val = 1 ; } else { val = 0 ; } } while (l1 != nullptr ) { cur->next = add (l1, nullptr , val); cur = cur->next; l1 = l1->next; if (cur->val >= 10 ) { cur->val -= 10 ; val = 1 ; } else { val = 0 ; } } while (l2 != nullptr ) { cur->next = add (l2, nullptr , val); cur = cur->next; l2 = l2->next; if (cur->val >= 10 ) { cur->val -= 10 ; val = 1 ; } else { val = 0 ; } } if (val) cur->next = new ListNode (1 ); return solution->next; } };