/**标签:ListNode,sum,next,carray,l2,l1,leetcode,两数 From: https://blog.51cto.com/u_15899033/5902958
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr;
ListNode *tail = nullptr;
ListNode *p = nullptr;
int sum = 0;
int carray = 0;
while (l1 != nullptr && l2 != nullptr) {
sum = l1->val + l2->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
if (nullptr == head) {
head = p;
}
else {
tail->next = p;
}
tail = p;
l1 = l1->next;
l2 = l2->next;
}
while (l1 != nullptr) {
sum = l1->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
tail->next = p;
tail = p;
l1 = l1->next;
}
while (l2 != nullptr) {
sum = l2->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
tail->next = p;
tail = p;
l2 = l2->next;
}
if (carray) {
p = new ListNode(carray);
tail->next = p;
}
return head;
}
};