题目
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解法:
按链表顺序往后遍历,保存进位值,注意链表指针问题
代码如下:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// 进位值缓存
int tmpValue = 0;
// 返回列表
ListNode* tar = NULL;
ListNode* tmpTar = NULL;
while (l1 != NULL || l2 != NULL || tmpValue > 0) {
int l1Val = l1 == NULL ? 0 : l1->val;
int l2Val = l2 == NULL ? 0 : l2->val;
int sum = l1Val + l2Val + tmpValue;
ListNode* tmpNode = new ListNode(sum % 10);
if (tmpTar)
{
tmpTar->next = tmpNode;
tmpTar = tmpNode;
}
else
{
tar = tmpNode;
tmpTar = tmpNode;
}
tmpValue = sum / 10;
if (l1)
l1 = l1->next;
if (l2)
l2 = l2->next;
}
return tar;
}
内存改良版本,将结果记录在l1并返回,代码如下:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// 进位值缓存
int tmpValue = 0;
// 返回列表
ListNode* tar = l1;
ListNode* tmpTar = l1;
ListNode* lastNode = NULL;
while (l1 != NULL || l2 != NULL || tmpValue > 0) {
int l1Val = l1 == NULL ? 0 : l1->val;
int l2Val = l2 == NULL ? 0 : l2->val;
int sum = l1Val + l2Val + tmpValue;
tmpValue = sum / 10;
if (l1)
{
if (l1->next)
l1 = l1->next;
else
l1 = NULL;
}
if (l2)
l2 = l2->next;
if (tmpTar) {
tmpTar->val = sum % 10;
if (!tmpTar->next) {
ListNode* tmpNode = new ListNode(0);
tmpTar->next = tmpNode;
lastNode = tmpTar;
}
tmpTar = tmpTar->next;
}
}
lastNode->next = NULL;
return tar;
}