You are given two linked lists representing two non-negative numbers. e 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
此算法虽然不具备什么难度,但是如果从抽象的推演到可运行的代码,其中有不少的细节需要注意。其中涉及到了进位问题,两个链表长度也可能不同,实现代码如下所示:
#include <iostream>
struct ListNode
{
int val;
ListNode* next;
ListNode(int _val)
{
val = _val;
}
};
class Solution
{
public:
ListNode* addTwoNumber(ListNode* l1, ListNode* l2)
{
static ListNode dummy(-1);
int carry = 0;
ListNode* prev = &dummy;
for(ListNode *pa=l1, *pb=l2;
pa != NULL || pb!= NULL;
pa = pa==NULL?NULL:pa->next,
pb = pb==NULL?NULL:pb->next,
prev = prev->next)
{
const int ai = pa==NULL?0:pa->val;
const int bi = pb==NULL?0:pb->val;
const int value = (ai+bi+carry) % 10;
carry = (ai+bi+carry)/10;
prev->next = new ListNode(value);
}
if ( carry > 0)
{
prev->next = new ListNode(carry);
}
prev->next->next = NULL;
return dummy.next;
}
void show(ListNode* ln)
{
for(; ln!= NULL; ln=ln->next)
{
printf("%d\n", ln->val);
}
}
};
int main()
{
ListNode l1(2), l2(3), l3(7);
l1.next = &l2;
l2.next = &l3;
l3.next = NULL;
ListNode k1(8), k2(5), k3(6);
k1.next = &k2;
k2.next = &k3;
k3.next = NULL;
Solution so;
ListNode* ad = so.addTwoNumber(&l1, &k1);
so.show(ad);
return 0;
}