问题描述
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
【解法一】
模拟十进制加法,两两合并,当一个list为空时复制领一个list即可,此时需注意处理最后进位的1
/**
* 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) {
ListNode listSum(0);
ListNode *pSum = &listSum;
int flag = 0;
int sum = 0;
while ((l1!=NULL) && (l2!=NULL))
{
sum = l1->val+ l2->val + flag;
// 计算是否要进位
flag = sum/10;
// 计算当前单位的值
pSum->next = new ListNode(sum%10);
// 指针跳转下一个节点
pSum = pSum->next;
// l1和l2推进
l1 = l1->next;
l2 = l2->next;
}
while (l1!=NULL)
{
sum = l1->val + flag;
flag = sum/10;
pSum->next = new ListNode(sum%10);
pSum = pSum->next;
l1 = l1->next;
}
while (l2!=NULL)
{
sum = l2->val + flag;
flag = sum/10;
pSum->next = new ListNode(sum%10);
pSum = pSum->next;
l2 = l2->next;
}
if (flag)
{
pSum->next = new ListNode(flag);
}
return listSum.next;
}
};
【解法二】
由解法可以看出来,每一步的结果实际上是相似的,只是省略为NULL和为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) {
ListNode listSum(0);
ListNode *pSum = &listSum;
int flag = 0;
int sum = 0;
while ((l1!=NULL) || (l2!=NULL) || flag)
{
sum = (l1?l1->val:0) + (l2?l2->val:0) + flag;
// 计算是否要进位
flag = sum/10;
// 计算当前单位的值
pSum->next = new ListNode(sum%10);
// 指针跳转下一个节点
pSum = pSum->next;
// l1和l2推进
l1 = l1 ?l1->next:l1;
l2 = l2 ?l2->next:l2;
}
return listSum.next;
}
};