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
+ * [Problem]: [21] Merge Two Sorted Lists
3
+ *
4
+ * (https://leetcode.com/problems/merge-two-sorted-lists/description/)
5
+ */
6
+
7
+ class ListNode {
8
+ val : number ;
9
+ next : ListNode | null ;
10
+ constructor ( val ?: number , next ?: ListNode | null ) {
11
+ this . val = val === undefined ? 0 : val ;
12
+ this . next = next === undefined ? null : next ;
13
+ }
14
+ }
15
+
16
+ function mergeTwoLists ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
17
+ //시간복잡도 O(m+n)
18
+ //공간복잡도 O(1)
19
+ function loopFunc ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
20
+ let current : ListNode = new ListNode ( ) ;
21
+ let dummy = current ;
22
+
23
+ while ( list1 !== null && list2 !== null ) {
24
+ if ( list1 . val < list2 . val ) {
25
+ current . next = list1 ;
26
+ list1 = list1 . next ;
27
+ } else {
28
+ current . next = list2 ;
29
+ list2 = list2 . next ;
30
+ }
31
+
32
+ current = current . next ;
33
+ }
34
+
35
+ current . next = list1 !== null ? list1 : list2 ;
36
+
37
+ return dummy . next ;
38
+ }
39
+
40
+ //시간복잡도 O(m+n)
41
+ //공간복잡도 O(m+n)
42
+ function recursionFunc ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
43
+ if ( list1 === null ) return list2 ;
44
+ if ( list2 === null ) return list1 ;
45
+
46
+ if ( list1 . val < list2 . val ) {
47
+ list1 . next = recursionFunc ( list1 . next , list2 ) ;
48
+ return list1 ;
49
+ } else {
50
+ list2 . next = recursionFunc ( list1 , list2 . next ) ;
51
+ return list2 ;
52
+ }
53
+ }
54
+
55
+ return recursionFunc ( list1 , list2 ) ;
56
+ }
You can’t perform that action at this time.
0 commit comments