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:链表为NULL 2: 两个链表不一样长, 3: 考虑之间的进位 4: 两个数字相加大于10。
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* resultHead = NULL;
ListNode* index = NULL;
int count = 0;
while(l1 != NULL && l2 != NULL)
{
int temp = count + l1->val + l2->val;
if(temp >= 10)
{
temp -= 10;
count = 1;
}
else
{
count = 0;
}
ListNode* curNode = new ListNode(temp);
if(resultHead == NULL)
{
resultHead = curNode;
index = resultHead;
}
else
{
index->next = curNode;
index = index->next;
}
l1 = l1->next;
l2 = l2->next;
}
ListNode *longList = (l1 == NULL ? l2 : l1);
while(longList)
{
int temp = count + longList->val;
if(temp >= 10)
{
temp -= 10;
count = 1;
}
else
{
count = 0;
}
ListNode* curNode = new ListNode(temp);
index->next = curNode;
index = index->next;
longList = longList->next;
}
if(count == 1)
{
index->next = new ListNode(count);
}
return resultHead;
}