題目:
You are given two linked lists representing two non-negative numbers.
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.Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
代碼:
/**
* 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) {
if(l1==NULL) return l2;
if(l2==NULL) return l1;
ListNode *resultHead = NULL ,*beforeNode = NULL;
int carry = 0;//當前進位
int a,b ;
bool flag = l1 || l2;//只有兩個都爲NULL時,纔有可能結束
int currentResult = 0;
while(flag||carry){//當進位爲0且l1,l2都爲NULL時,才結束
ListNode *resultNode = new ListNode(0);
if(resultHead == NULL){
resultHead = resultNode;
beforeNode = resultHead;
}
else{
beforeNode->next = resultNode;
beforeNode = resultNode;
}
a = l1 ? (l1->val) : 0;//當l爲空時,將其內容當成0
b = l2 ? (l2->val) : 0;
currentResult = a + b + carry;
resultNode->val = currentResult % 10;
carry = currentResult / 10;
//當l爲NULL時,沒有next,一定要讓其保持爲NULL
l1 = l1 ? l1->next:l1;
l2 = l2 ? l2->next:l2;
flag = l1 || l2;
}
return resultHead;
}
};
注:由於兩個列表可能長度不同,所以這裏採用了補齊的方法,將短列表後面的內容都當成0。