Add Two Numbers
[Problem Link]
Description
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Solution 1
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int flag = 0;
ListNode* ansHead = new ListNode(0);
ListNode* cur = ansHead;
while (1) {
int sum = 0;
if (flag == 1) {
sum += 1;
flag = 0;
}
if (l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->val;
l2 = l2->next;
}
if (sum > 9) {
sum -= 10;
flag = 1;
}
cur->val = sum;
if (l1 == NULL && l2 == NULL && flag == 0) {
break;
}
cur->next = new ListNode(0);
cur = cur->next;
}
return ansHead;
}
};
Solution 2
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode preHead(0), *p = &preHead;
int extra = 0;
while (l1 || l2 || extra) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
extra = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return preHead.next; //不要第一個自己隨意賦的值,好方法
}
};
Summary
- 看起來像是一道很簡單的題,但是我卻通過這道題發現了自己對指針掌握的不足。因爲要返回一個鏈表,在鏈表的循環創建中指針是不斷向下指的(ans),所以肯定要保留一個頭結點(anshead)。就是在鏈表和鏈表頭結點上,我糾結了很久。
首先,定義
anshead = new ListNode(0);
ans = anshead;
必須先給anshead分配內存,再把ans指向anshead分配的空間中,每次也必須先給 ans->next = new ListNode(0) 賦值後才能寫 ans = ans->next;
總之,必須把ans 指向一個開闢過的空間。
否則, pre->next 在未開闢時指向 0x00000000 若這時 ans = pre->next 那麼ans也是0x00000000 若這時給 ans 分配了空間,pre->next 還是0x00000000 因爲之前ans沒有明確的指定一個地方。 - 做鏈表題目時要返回鏈表頭,可以將鏈表頭隨意賦值,最後return 鏈表頭.next,這樣可以不用多一個指針存儲鏈表頭。