File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time complexity: O(n)
2
+ // Space complexity: O(n)
3
+
4
+ /**
5
+ * Definition for singly-linked list.
6
+ * function ListNode(val, next) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.next = (next===undefined ? null : next)
9
+ * }
10
+ */
11
+ /**
12
+ * @param {ListNode } head
13
+ * @return {void } Do not return anything, modify head in-place instead.
14
+ */
15
+ var reorderList = function ( head ) {
16
+ const nodes = [ ] ;
17
+ let n = 0 ;
18
+
19
+ {
20
+ let current = head ;
21
+ while ( current ) {
22
+ n ++ ;
23
+ nodes . push ( current ) ;
24
+ current = current . next ;
25
+ }
26
+ }
27
+
28
+ const answer = head ;
29
+
30
+ {
31
+ let current = answer ;
32
+ for ( let i = 1 ; i < n ; i ++ ) {
33
+ if ( i % 2 !== 0 ) {
34
+ current . next = nodes . at ( n - Math . ceil ( i / 2 ) ) ;
35
+ } else {
36
+ current . next = nodes . at ( i / 2 ) ;
37
+ }
38
+
39
+ current = current . next ;
40
+ }
41
+
42
+ current . next = null ;
43
+ }
44
+
45
+ return answer ;
46
+ } ;
You can’t perform that action at this time.
0 commit comments