## Clairezz_的博客

Never give up！

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

36ms

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (l2 == NULL) return l1;
if (l1 == NULL) return l2;
int digit = (l1->val + l2->val) % 10;
int carry = (l1->val + l2->val) / 10;
ListNode *p1 = l1->next, *p2 = l2->next;
while (p1 != NULL && p2 != NULL){
digit = (p1->val + p2->val + carry) % 10;
carry = (p1->val + p2->val + carry) / 10;
ListNode *p = new ListNode(digit);
tail->next = p;
tail = p;
p1 = p1->next;
p2 = p2->next;
}
ListNode *pp = p1;
if (p2 != NULL) pp = p2;
while (pp != NULL){
digit = (pp->val + carry) % 10;
carry = (pp->val + carry) / 10;
ListNode *p = new ListNode(digit);
tail->next = p;
tail = p;
pp = pp->next;
}
if (carry != 0){
ListNode *p = new ListNode(carry);
tail->next = p;
}
}
};

2016-11-21 12:05:45

2016-11-23 11:14:19

#### [LeetCode] 002. Add Two Numbers (Medium) (C++/Java/Python)

2015-02-27 12:43:08

#### [C++]LeetCode: 108 Add Two Numbers (反序链表求和)

2015-01-18 17:15:23

#### 【LeetCode with Python】 Add Two Numbers

2014-06-27 18:11:19

2017-06-04 14:55:04

2016-11-16 22:06:30