Skip to content

Commit 7ee873d

Browse files
committed
Merge two sorted lists
1 parent 923dfdd commit 7ee873d

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# μ—°κ΄€ 링크
2+
- [문제 풀이 μŠ€μΌ€μ€„](https://github.com/orgs/DaleStudy/projects/6/views/5)
3+
- [λ‹΅μ•ˆ μ½”λ“œ μ œμΆœλ²•](https://github.com/DaleStudy/leetcode-study/wiki/%EB%8B%B5%EC%95%88-%EC%A0%9C%EC%B6%9C-%EA%B0%80%EC%9D%B4%EB%93%9C)
4+
5+
# Problem
6+
- 문제 링크 : http://leetcode.com/problems/merge-two-sorted-lists/
7+
- 문제 이름 : Merge Two Sorted Lists
8+
- 문제 번호 : 21
9+
- λ‚œμ΄λ„ : easy
10+
- μΉ΄ν…Œκ³ λ¦¬ :
11+
12+
# 문제 μ„€λͺ…
13+
14+
15+
# 아이디어
16+
- μ–΄λ–€ λ°©λ²•μœΌλ‘œ μ ‘κ·Όν–ˆλŠ”μ§€ μ„œμˆ 
17+
- 포슀 vs μ΅œμ ν™” 아이디어 차이 λ“±
18+
- μž‘λ„μ— λŒ€ν•œ κ³ λ €
19+
20+
# βœ… μ½”λ“œ (Solution)
21+
##
22+
```cpp
23+
/**
24+
* Definition for singly-linked list.
25+
* struct ListNode {
26+
* int val;
27+
* ListNode *next;
28+
* ListNode() : val(0), next(nullptr) {}
29+
* ListNode(int x) : val(x), next(nullptr) {}
30+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
31+
* };
32+
*/
33+
class Solution {
34+
public:
35+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
36+
auto head = new ListNode();
37+
auto cur = head;
38+
39+
while(true){
40+
if(list1 == nullptr && list2 == nullptr){
41+
break;
42+
}
43+
if(list1==nullptr){
44+
cur->next = new ListNode(list2->val);
45+
list2 = list2->next;
46+
cur = cur->next;
47+
continue;
48+
}
49+
50+
if(list2 == nullptr){
51+
cur->next = new ListNode(list1->val);
52+
list1 = list1->next;
53+
cur = cur->next;
54+
continue;
55+
}
56+
57+
if(list1->val > list2->val){
58+
cur->next = new ListNode(list2->val);
59+
list2 = list2->next;
60+
cur = cur->next;
61+
continue;
62+
}else{
63+
cur->next = new ListNode(list1->val);
64+
list1 = list1->next;
65+
cur = cur->next;
66+
continue;
67+
}
68+
69+
70+
}
71+
72+
return head->next;
73+
}
74+
};
75+
76+
```
77+
78+
## κ°„μ†Œν™” 버전
79+
```cpp
80+
class Solution {
81+
public:
82+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
83+
ListNode dummy;
84+
ListNode* cur = &dummy;
85+
86+
while (list1 && list2) {
87+
if (list1->val < list2->val) {
88+
cur->next = list1;
89+
list1 = list1->next;
90+
} else {
91+
cur->next = list2;
92+
list2 = list2->next;
93+
}
94+
cur = cur->next;
95+
}
96+
97+
cur->next = list1 ? list1 : list2;
98+
99+
return dummy.next;
100+
}
101+
};
102+
103+
```
104+
105+
- 인자 μˆ˜μ • -> λ©”λͺ¨λ¦¬ μž¬ν™œμš©
106+
107+
# πŸ” μ½”λ“œ μ„€λͺ…
108+
109+
110+
# μ΅œμ ν™” 포인트 (Optimality Discussion)
111+
β€’ μ΅œμ ν™”ν•œ μ΄μœ μ™€ 원리
112+
β€’ 더 쀄일 수 μžˆλŠ” μ—¬μ§€λŠ” μžˆλŠ”κ°€?
113+
β€’ κΈ°μ‘΄ 방법 λŒ€λΉ„ μ–Όλ§ˆλ‚˜ νš¨μœ¨μ μ΄μ—ˆλŠ”μ§€
114+
115+
# πŸ§ͺ ν…ŒμŠ€νŠΈ & μ—£μ§€ μΌ€μ΄μŠ€
116+
117+
# πŸ“š κ΄€λ ¨ 지식 볡슡
118+
119+
# πŸ” 회고
120+
121+

0 commit comments

Comments
Β (0)