File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 문제 설명
3+ * - k개의 정렬된 링크드 리스트 병합하기
4+ *
5+ * 아이디어
6+ * 1) 병합정렬 -> 대표적인 분할 정복(Divide and Conquer) 문제
7+ * - 두 리스트를 병합할 수 있는 함수를 계속해서 적용한다.
8+ * - 두 링크드 리스트 병합하는 예제
9+ * ㄴ @link https://leetcode.com/problems/merge-two-sorted-lists/description/
10+ *
11+ */
12+ /**
13+ * Definition for singly-linked list.
14+ * class ListNode {
15+ * val: number
16+ * next: ListNode | null
17+ * constructor(val?: number, next?: ListNode | null) {
18+ * this.val = (val===undefined ? 0 : val)
19+ * this.next = (next===undefined ? null : next)
20+ * }
21+ * }
22+ */
23+
24+ class ListNode {
25+ val : number ;
26+ next : ListNode | null ;
27+ constructor ( val ?: number , next ?: ListNode | null ) {
28+ this . val = val === undefined ? 0 : val ;
29+ this . next = next === undefined ? null : next ;
30+ }
31+ }
32+
33+ function mergeList ( list1 : ListNode | null , list2 : ListNode | null ) {
34+ const dummy = new ListNode ( 0 ) ;
35+ let current = dummy ;
36+
37+ while ( list1 && list2 ) {
38+ if ( list1 . val <= list2 . val ) {
39+ current . next = list1 ;
40+ list1 = list1 . next ;
41+ } else {
42+ current . next = list2 ;
43+ list2 = list2 . next ;
44+ }
45+ current = current . next ;
46+ }
47+ current . next = list1 || list2 ;
48+
49+ return dummy . next ;
50+ }
51+
52+ function mergeKLists ( lists : Array < ListNode | null > ) : ListNode | null {
53+ return lists . reduce ( ( acc , current ) => {
54+ return mergeList ( acc , current ) ;
55+ } , null ) ;
56+ }
You can’t perform that action at this time.
0 commit comments