Problem:
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
Analysis:
Simple digit addition, pay attention to carry.
To save space here, we try to merge l2 into l1. This allow us implement a in-place solution.
Code:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 if (l1 == NULL) return l2; 15 if (l2 == NULL) return l1; 16 17 int carry = 0; 18 ListNode *dummy = new ListNode(0); 19 dummy->next = l1; 20 while ((dummy->next != NULL) && (l2 != NULL)) { 21 dummy = dummy->next; 22 int sum = dummy->val + l2->val + carry; 23 dummy->val = sum%10; 24 carry = sum / 10; 25 26 l2 = l2->next; 27 } 28 29 if (l2 != NULL) 30 dummy->next = l2; 31 32 while (dummy->next != NULL) { 33 dummy = dummy->next; 34 if (carry != 0) { 35 int sum = dummy->val + carry; 36 dummy->val = sum % 10; 37 carry = sum /10; 38 } else { 39 break; 40 } 41 } 42 43 if (carry == 1) 44 dummy->next = new ListNode(1); 45 46 return l1; 47 } 48 };