002 - Add Two Number

解碼

pointer 處理

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode();
ListNode* cur = head;

int sum = 0;
while(1){
if(l1 != nullptr){
sum += l1->val;
l1 = l1->next;
}
if(l2 != nullptr){
sum += l2->val;
l2 = l2->next;
}

cur->val = sum % 10;
sum /= 10;
//當沒有更大位數能加且不處理進位問題, break;
if(l1 == nullptr && l2 == nullptr && sum == 0) break;
cur->next = new ListNode();
cur = cur->next;
}
return head;
}
};
  • 版權聲明: 本部落格所有文章除有特別聲明外,均採用 Apache License 2.0 許可協議。轉載請註明出處!
  • © 2020-2024 John Doe
  • Powered by Hexo Theme Ayer
  • PV: UV: