問題描述
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);
// 指針跳轉下一個節(jié)點
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);
// 指針跳轉下一個節(jié)點
pSum = pSum->next;
// l1和l2推進
l1 = l1 ?l1->next:l1;
l2 = l2 ?l2->next:l2;
}
return listSum.next;
}
};