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
问题描述:给定两个链表,每个链表当中代表两个非负数字,根据输入和输出可以看到
输入: 2 4 3
5 6 4
输出: 7 0 8
可以看出根据链表依次进行相加小于10,则直接添加在新建列表中,如果大于10,则存储进位值,作为下一节点的值进行添加
class Solution {
private:
ListNode* ret;
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head_1 = l1,*head_2=l2;
int index = 0;
int value = 0;
int high_value = 0;
ret= new ListNode(0);
ListNode* last_ret = ret;
while (head_1 != NULL&&head_2 != NULL)
{
value = head_1->val + head_2->val+high_value;
if (value < 10)
{
high_value = 0;
last_ret->val = value;
}
else
{
high_value = value / 10;
value = value % 10;
last_ret->val = value;
}
head_1 = head_1->next;
head_2 = head_2->next;
if (head_1 != NULL&&head_2 != NULL)
{
last_ret->next = new ListNode(0);
last_ret = last_ret->next;
}
}
ListNode* cur = NULL;
if (head_1 != NULL)
{
cur = head_1;
}
else
{
cur = head_2;
}
if (cur != NULL)
{
last_ret->next = new ListNode(0);
last_ret = last_ret->next;
while (cur != NULL)
{
value = cur->val + high_value;
if (value < 10)
{
high_value = 0;
}
else
{
high_value = value / 10;
value = value % 10;
}
last_ret->val = value;
cur = cur->next;
if (cur != NULL)
{
last_ret->next = new ListNode(0);
last_ret = last_ret->next;
}
}
}
if (high_value > 0)
{
last_ret->next = new ListNode(0);
last_ret = last_ret->next;
last_ret->val = high_value;
}
return ret;
}
~Solution()
{
ListNode* cur = NULL;
cur = ret;
while (cur != NULL)
{
ListNode* m = cur;
if (cur != NULL)
{
cur = cur->next;
}
if(m)
delete m;
}
}
};