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) {
if(l1 == nullptr && l2 == nullptr)
return nullptr;
else if(l1 == nullptr)
return l2;
else if(l2 == nullptr)
return l1;
int a = l1->val + l2->val;
ListNode* p = new ListNode(a % 10);
p->next = addTwoNumbers(l1->next, l2->next);
if(a >= 10)
p->next = addTwoNumbers(p->next, new ListNode(1));
return p;
}
在递归法中,先确定递归的收敛条件,然后确定正常的递归逻辑,最后考虑特殊情况,本题中为考虑末位进一的情况,形成最终代码。
一般解法:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ret = new ListNode(0);
ListNode* tmp = ret;
int sum = 0;
while(l1 || l2)
{
if(l1)
{
sum += l1->val;
l1 = l1->next;
}
if(l2)
{
sum += l2->val;
l2 = l2->next;
}
tmp->next = new ListNode(sum % 10);
sum /= 10;
tmp = tmp->next;
}
if(sum) //carry last bit
{
tmp->next = new ListNode(1);
}
return ret->next;
}
注意在一般解法中,一般先new出来一个节点,然后使用一个临时节点用来遍历。需说明的是,本题牺牲了值为0的头节点。