Skip to content

Commit 3b1d109

Browse files
committed
4주차 문제 풀이 2개 추가
- Merge Two Sorted Lists - Maximum Depth of Binary Tree
1 parent bb1b12e commit 3b1d109

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
14+
ListNode dummy; // head 초기화의 복잡성을 낮추기 위한 더미노드
15+
ListNode* tail = &dummy;
16+
17+
while (list1 != nullptr && list2 != nullptr)
18+
{
19+
if (list1->val < list2->val)
20+
{
21+
tail->next = list1;
22+
list1 = list1->next;
23+
}
24+
else
25+
{
26+
tail->next = list2;
27+
list2 = list2->next;
28+
}
29+
30+
tail = tail->next;
31+
}
32+
33+
tail->next = (list1 == nullptr) ? list2 : list1;
34+
35+
return dummy.next;
36+
}
37+
}
38+
;
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
14+
ListNode dummy; // head 초기화의 복잡성을 낮추기 위한 더미노드
15+
ListNode* tail = &dummy;
16+
17+
while (list1 != nullptr && list2 != nullptr)
18+
{
19+
if (list1->val < list2->val)
20+
{
21+
tail->next = list1;
22+
list1 = list1->next;
23+
}
24+
else
25+
{
26+
tail->next = list2;
27+
list2 = list2->next;
28+
}
29+
30+
tail = tail->next;
31+
}
32+
33+
tail->next = (list1 == nullptr) ? list2 : list1;
34+
35+
return dummy.next;
36+
}
37+
}
38+
;

0 commit comments

Comments
 (0)