原題:
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
對兩個鏈表做加法,每個結點的值只能是個位數,向后進位;
對于兩個鏈表不一樣長的情況,可以讓短的鏈表后面的值都為0,也可以直接把長的鏈表多余的部分鏈接到ans鏈表的尾。但在本題中,因為要處理進位,如果兩個鏈表分別是[1];[9,9,9,9],結果是[0,0,0,0,1],不能直接把多余的連接到表尾,因此采用第一種處理方式。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode(0);
ListNode* P = ans; // P指向結果鏈表的最后一位
int count = 0;
while(l1 || l2){
if(l1){
count += l1->val;
l1 = l1->next;
}
if(l2){
count += l2->val;
l2 = l2->next;
}
P->next = new ListNode(count % 10);
P = P->next;
count /= 10;
}
if(count) { // 如果l1,l2都為空,但剩余一個進位,需要新增加結點
P->next = new ListNode(1);
}
return ans->next;
}
};