File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ class ListNode {
2
+ val : number
3
+ next : ListNode | null
4
+ constructor ( val ?: number , next ?: ListNode | null ) {
5
+ this . val = ( val === undefined ? 0 : val )
6
+ this . next = ( next === undefined ? null : next )
7
+ }
8
+ }
9
+
10
+ /**
11
+ * λ κ°μ μ λ ¬λ μ°κ²° 리μ€νΈλ₯Ό λ³ν©νμ¬ νλμ μ λ ¬λ μ°κ²° 리μ€νΈλ₯Ό λ°ννλ ν¨μ
12
+ * @param {ListNode | null } list1 - 첫 λ²μ§Έ μ λ ¬λ μ°κ²° 리μ€νΈ
13
+ * @param {ListNode | null } list2 - λ λ²μ§Έ μ λ ¬λ μ°κ²° 리μ€νΈ
14
+ * @returns {ListNode | null } - λ³ν©λ μ λ ¬λ μ°κ²° 리μ€νΈ
15
+ *
16
+ * μκ° λ³΅μ‘λ: O(n + m)
17
+ * - n: list1μ λ
Έλ κ°μ
18
+ * - m: list2μ λ
Έλ κ°μ
19
+ *
20
+ * κ³΅κ° λ³΅μ‘λ: O(1)
21
+ * - μλ‘μ΄ λ
Έλλ₯Ό μμ±νμ§ μκ³ κΈ°μ‘΄ λ
Έλμ ν¬μΈν°λ₯Ό μ‘°μ νμ¬ λ³ν©νλ―λ‘ μΆκ° κ³΅κ° μ¬μ© μμ
22
+ */
23
+
24
+ function mergeTwoLists ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
25
+ // null μμΈ μ²λ¦¬
26
+ if ( ! list1 || ! list2 ) return list1 || list2 ;
27
+
28
+ // μμμ μ μν λλ―Έ ν€λ λ
Έλ μμ±
29
+ const start = new ListNode ( - 101 ) ;
30
+ let current = start ;
31
+
32
+ // λ 리μ€νΈλ₯Ό μμ°¨μ μΌλ‘ λΉκ΅νλ©° λ³ν©
33
+ while ( list1 !== null && list2 !== null ) {
34
+ if ( list1 . val <= list2 . val ) {
35
+ current . next = list1 ;
36
+ list1 = list1 . next ;
37
+ } else {
38
+ current . next = list2 ;
39
+ list2 = list2 . next ;
40
+ }
41
+ current = current . next ;
42
+ }
43
+
44
+ // λ¨μ λ
Έλλ₯Ό μ°κ²° (list1 λλ list2 μ€ νλλ null μν)
45
+ current . next = list1 !== null ? list1 : list2 ;
46
+
47
+ // λλ―Έ ν€λμ λ€μ λ
Έλκ° μ€μ λ³ν©λ 리μ€νΈμ μμ
48
+ return start . next ;
49
+ }
You canβt perform that action at this time.
0 commit comments