Leetcode Add Two Numbers
8434 ワード
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode* p = l1;
ListNode* q = l2;
ListNode* ret = NULL;
ListNode* ret_cur = NULL;
int carry = 0;
int digit = 0;
while (p != NULL && q != NULL) {
carry = add_node(p->val + q->val + carry, ret, ret_cur);
p = p->next;
q = q->next;
}
while (p != NULL) {
carry = add_node(p->val + carry, ret, ret_cur);
p = p->next;
}
while (q != NULL) {
carry = add_node(q->val + carry, ret, ret_cur);
q = q->next;
}
if (carry) add_node(1, ret, ret_cur);
return ret;
}
int add_node(int val, ListNode* &head, ListNode* &cur) {
int carry = val / 10;
int digit = carry == 0 ? val : val - 10;
ListNode* cur_res = new ListNode(digit);
if (head == NULL) {
head = cur_res;
cur = cur_res;
} else {
cur->next = cur_res;
cur = cur_res;
}
return carry;
}
};
1発の水.
第2ラウンド:
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
空のチェーンヘッダーを追加して、空の値の判断を簡略化します.
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
12 ListNode holder(0);
13 ListNode* prev = &holder;
14
15 int carry = 0;
16 while (l1 != NULL && l2 != NULL) {
17 int sum = l1->val + l2->val + carry;
18 carry = sum / 10;
19 prev->next = new ListNode(sum % 10);
20 prev = prev->next;
21 l1 = l1->next;
22 l2 = l2->next;
23 }
24
25 ListNode* last = (l1 == NULL) ? l2 : l1;
26
27 while (last != NULL) {
28 int sum = last->val + carry;
29 carry = sum/10;
30 prev->next = new ListNode(sum % 10);
31 last = last->next;
32 prev = prev->next;
33 }
34
35 if (carry) {
36 prev->next = new ListNode(1);
37 }
38
39 return holder.next;
40 }
41 };