File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ // ✅ Time Complexity: O(N)
2+ // ✅ Space Complexity: O(N) (due to the stack storage)
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+ /**
13+ * @param {ListNode } head
14+ * @return {void } Do not return anything, modify head in-place instead.
15+ */
16+ var reorderList = function ( head ) {
17+ let stack = [ ] ;
18+ let node = head ;
19+
20+ while ( node ) {
21+ stack . push ( node ) ;
22+ node = node . next ;
23+ }
24+
25+ let dummy = new ListNode ( - 1 ) ;
26+ node = dummy ;
27+
28+ const len = stack . length ;
29+
30+ for ( let i = 0 ; i < len ; i ++ ) {
31+ if ( i % 2 === 1 ) {
32+ node . next = stack . pop ( ) ;
33+ } else {
34+ node . next = head ;
35+ head = head . next ;
36+ }
37+ node = node . next ;
38+ }
39+
40+ node . next = null ;
41+ return dummy . next ;
42+ } ;
43+
You can’t perform that action at this time.
0 commit comments