File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-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
+ * https://leetcode.com/problems/reorder-list
12
+ * T.C. O(n)
13
+ * S.C. O(1)
14
+ */
15
+ function reorderList ( head : ListNode | null ) : void {
16
+ if ( ! head || ! head . next ) return ;
17
+
18
+ let fast : ListNode | null = head ;
19
+ let slow : ListNode | null = head ;
20
+
21
+ while ( fast && fast . next ) {
22
+ fast = fast . next . next ;
23
+ slow = slow ! . next ;
24
+ }
25
+
26
+ let prev : ListNode | null = null ;
27
+ let curr : ListNode | null = slow ;
28
+ while ( curr ) {
29
+ const next = curr . next ;
30
+ curr . next = prev ;
31
+ prev = curr ;
32
+ curr = next ;
33
+ }
34
+
35
+ let front : ListNode | null = head ;
36
+ let back : ListNode | null = prev ;
37
+ while ( back ! . next ) {
38
+ const frontNext = front ! . next ;
39
+ const backNext = back ! . next ;
40
+
41
+ front ! . next = back ;
42
+ back ! . next = frontNext ;
43
+
44
+ front = frontNext ;
45
+ back = backNext ;
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments