给定两个非空链表来代表两个非负整数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
/**
* 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) {
if(NULL == l1)
return l2;
if(NULL == l2)
return l1;
bool temp = false;
ListNode* lNew, *lHead, *lRe;
lRe = new ListNode(0);
lRe->val = l1->val + l2->val;
if(lRe->val >= 10)
{
lRe->val -= 10;
temp = true;
}
l1 = l1->next;
l2 = l2->next;
lHead = lRe;
while(NULL != l1 || NULL != l2)
{
lNew = new ListNode(0);
if(temp)
{
lNew->val += 1;
temp = false;
}
if(NULL != l1)
{
lNew->val += l1->val;
l1 = l1->next;
}
if(NULL != l2)
{
lNew->val += l2->val;
l2 = l2->next;
}
if(lNew->val >= 10)
{
lNew->val -= 10;
temp = true;
}
lRe->next = lNew;
lRe = lRe->next;
}
if(temp)
{
lNew = new ListNode(1);
lRe->next = lNew;
}
return lHead;
}