Skip to content

Commit 97c6d2a

Browse files
committed
add: solve DaleStudy#224 Merge Two Sorted Lists with ts
1 parent 03ded85 commit 97c6d2a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

β€Žmerge-two-sorted-lists/Yjason-K.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

0 commit comments

Comments
Β (0)