试题
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
试题大意
把两个整数分别用两个反序链表的形式来表示(十进制表示法的从低位到高位依次存入链表)。对这两个整数求和。结果依然以反序链表表示。
解题思路
这是纯粹的十进制大数加法模拟题。
循环遍历链表。对于每轮循环,记录第一个链表(如果未遍历到末尾)与第二个链表(如果未遍历到末尾)与上次进位之和。把结果的个位数放在新链表末尾,记录进位,供下次使用。最后一次要把进位(如果不是0)插入新链表末尾。
源代码
/**
* 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) {
int carry = 0, current_digit = 0;
ListNode* result = NULL;
while (l1 != NULL || l2 != NULL)
{
current_digit = carry;
if (l1 != NULL)
{
current_digit += l1->val;
l1 = l1->next;
}
if (l2 != NULL)
{
current_digit += l2->val;
l2 = l2->next;
}
carry = current_digit / 10;
current_digit %= 10;
ListNode *temp = new ListNode(current_digit);
appendNode(result, (new ListNode(current_digit)));
}
if (carry != 0)
appendNode(result, (new ListNode(carry)));
return result;
}
private:
void appendNode(ListNode *&l, ListNode *e)
{
if (l == NULL)
{
l = e;
return;
}
ListNode *q = l;
ListNode *p = q->next;
while (p != NULL)
{
q = p;
p = q->next;
}
q->next = e;
}
};