LEETCODE專題
Add Two Numbers
首先先上題目:
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
下面是一些個人理解和細節把握:
鏈表的每個節點其實都可以相加然後往下走到下一個節點,但是要把握好前提條件:
- 兩個鏈表要保持同一個深度
- 每一個節點相加後的進位要存儲至結果鏈表的下一個節點
這些都是可以做到的,下面有代碼,在這裏不再贅述
2.在1[1]的基礎上提出問題:倘若兩個鏈表不等長怎麼辦?
這時候就加一個條件判斷就能夠解決問題
3.最後倘若兩個輸入鏈表已經結束然而進位爲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) {
bool first = true; // firstly enter the while block
int carry = 0; // carry = 1 or 0
ListNode * sum = new ListNode(0); // store the sum of l1 and l2
ListNode * head_of_sum = sum; // return the head of ListNode * sum
while (l1 != NULL || l2 != NULL) {
int temp_sum = carry;
if (first == false) {
sum->next = new ListNode(0);
sum = sum->next;
} else {
first = false;
}
if (l1 == NULL) {
temp_sum += l2->val;
} else if (l2 == NULL) {
temp_sum += l1->val;
} else {
temp_sum += l1->val + l2->val;
}
carry = temp_sum / 10;
sum->val = temp_sum % 10;
if (l1 != NULL) {
l1 = l1->next;
}
if (l2 != NULL) {
l2 = l2->next;
}
}
if (carry == 1) {
sum->next = new ListNode(carry);
}
return head_of_sum;
}
};