題目
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.
兩個鏈表相加阳准,鏈表中均為非負(fù)整數(shù)竞端。鏈表中的整數(shù)以倒序存放讲岁,即開頭為個位厢钧,然后依次為十位勤哗、百位媳友、千位等等……將相加之和以一個鏈表的結(jié)構(gòu)返回肥缔。
- Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解題思路
思路很簡單,同時循環(huán)兩個鏈表巩掺,然后將相加的結(jié)果儲存在新的鏈表中偏序。但是題目有兩個難點:
- 兩個鏈表長度可能不相等:
- 解決方法是在短的鏈表尾部補0,然后與長鏈表相加
- 當(dāng)相加的和大于10時胖替,需要進(jìn)位:
- 設(shè)置一個變量默認(rèn)值為0研儒,當(dāng)和大于10時,變量的值為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 sum(0), *p = ∑
int carry = 0;
while(l1!=NULL || l2!=NULL || carry!=0) { // carry != 0 應(yīng)對特殊情況如:【6】+【7】或者【64】+【36】端朵,即,兩個相同長度的鏈表相加產(chǎn)生進(jìn)位的情況
if(l1) { // 循環(huán) l1
carry += l1->val;
l1 = l1->next;
}
if(l2) { // 循環(huán) l2
carry += l2->val;
l2 = l2->next;
}
p->next = new ListNode(carry%10);
carry = carry/10; // 保存進(jìn)位
p = p->next;
}
return sum.next;
}
};