File tree Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * [Problem]: [143] Reorder List
3
+ * (https://leetcode.com/problems/reorder-list/)
4
+ */
5
+
6
+ class ListNode {
7
+ val : number ;
8
+ next : ListNode | null ;
9
+ constructor ( val ?: number , next ?: ListNode | null ) {
10
+ this . val = val === undefined ? 0 : val ;
11
+ this . next = next === undefined ? null : next ;
12
+ }
13
+ }
14
+
15
+ /**
16
+ Do not return anything, modify head in-place instead.
17
+ */
18
+ function reorderList ( head : ListNode | null ) : void {
19
+ //시간복잡도 O(n)
20
+ //공간복잡도 O(n)
21
+ function stackFunc ( head : ListNode | null ) : void {
22
+ if ( ! head || ! head . next ) return ;
23
+
24
+ const stack : ListNode [ ] = [ ] ;
25
+ let node : ListNode | null = head ;
26
+
27
+ while ( node ) {
28
+ stack . push ( node ) ;
29
+ node = node . next ;
30
+ }
31
+
32
+ const length = stack . length ;
33
+ node = head ;
34
+
35
+ for ( let i = 0 ; i < Math . floor ( length / 2 ) ; i ++ ) {
36
+ const tail = stack . pop ( ) ! ;
37
+ const next : ListNode | null = node . next ;
38
+
39
+ node . next = tail ;
40
+ tail . next = next ;
41
+
42
+ node = next ! ;
43
+ }
44
+
45
+ node . next = null ;
46
+ }
47
+ //시간복잡도 O(n)
48
+ //공간복잡도 O(1)
49
+ function twoPointerFunc ( head : ListNode | null ) : void {
50
+ if ( ! head || ! head . next ) return ;
51
+
52
+ let slow = head ;
53
+ let fast = head ;
54
+ while ( fast && fast . next && fast . next . next ) {
55
+ slow = slow . next ! ;
56
+ fast = fast . next . next ;
57
+ }
58
+
59
+ let prev : ListNode | null = null ;
60
+ let curr = slow . next ;
61
+ slow . next = null ;
62
+
63
+ while ( curr ) {
64
+ const next = curr . next ;
65
+ curr . next = prev ;
66
+ prev = curr ;
67
+ curr = next ;
68
+ }
69
+
70
+ let first = head ;
71
+ let second = prev ;
72
+
73
+ while ( second ) {
74
+ const tmp1 = first ! . next ;
75
+ const tmp2 = second . next ;
76
+
77
+ first ! . next = second ;
78
+ second . next = tmp1 ;
79
+
80
+ first = tmp1 ! ;
81
+ second = tmp2 ;
82
+ }
83
+ }
84
+ }
You can’t perform that action at this time.
0 commit comments