[LeetCode] [Medium] Add Two Numbers (linked list)
2021. 3. 17. 23:19ㆍ알고리즘/LeetCode
1. Problems
Given two num list
Add the two numbers and return the sum
2. Sol
I use triple pointer for update double pointer.
Becuse double pointer have address of answer list and I don't want to change value of answer list.
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
|
/**
* 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:
void pushList(ListNode*** l0, int sum) {
if(**l0 == nullptr)
**l0 = new ListNode(sum);
else
{
(**l0)->next = new ListNode(sum);
*l0 = &((**l0)->next);
}
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ret = nullptr;
ListNode** tmp = &ret;
int carry = 0;
while(l1||l2||carry)
{
int sum = carry;
if(l1) sum += l1->val, l1 = l1->next;
if(l2) sum += l2->val, l2 = l2->next;
pushList(&tmp, sum%10);
carry = sum/10;
}
return ret;
}
};
|
cs |
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] [C++] Reverse Integer (0) | 2021.05.11 |
---|---|
[LeetCode] [Medium] ZigZag Conversion (0) | 2021.03.21 |
[LeetCode] [Medium] Longest Palindromic Substring (dp) (0) | 2021.03.20 |
[LeetCode] [Medium] Longest Substring Without Repeating Characters (0) | 2021.03.18 |
[LeetCode] [easy] Two Sum (brute-force, map) (0) | 2021.03.16 |