You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
1 class Solution { 2 public: 3 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 4 ListNode dummy(0); 5 ListNode *p = &dummy; 6 ListNode *p1 = l1, *p2 = l2; 7 8 int carry = 0; 9 10 while (p1 || p2){ 11 int n1 = p1 ? p1->val : 0; 12 int n2 = p2 ? p2->val : 0; 13 int sum = n1 + n2 + carry; 14 carry = sum / 10; 15 p->next = new ListNode(sum % 10); 16 p = p->next; 17 if (p1) p1 = p1->next; 18 if (p2) p2 = p2->next; 19 } 20 21 if (carry){ 22 p->next = new ListNode(carry); 23 } 24 25 return dummy.next; 26 } 27 };