File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ // First option : change node value
12var reorderList = function ( head ) {
23 if ( ! head ) return ;
34 // Create new arr to return result and current head
@@ -24,3 +25,44 @@ var reorderList = function (head) {
2425
2526// TC: O(n)
2627// SC: O(n)
28+
29+ // Second option : move node without changing values
30+ var reorderList = function ( head ) {
31+ // Edge case
32+ if ( ! head ) return ;
33+
34+ // Find mid node from linked list
35+ let slow = head ,
36+ fast = head ;
37+ while ( fast && fast . next ) {
38+ slow = slow . next ;
39+ fast = fast . next . next ;
40+ }
41+
42+ // Reverse second half list
43+ let prev = null ,
44+ curr = slow ,
45+ temp ;
46+ while ( curr ) {
47+ temp = curr . next ;
48+ curr . next = prev ;
49+ prev = curr ;
50+ curr = temp ;
51+ }
52+
53+ // Modify linked list as followed instruction
54+ let first = head ,
55+ second = prev ;
56+ while ( second . next ) {
57+ temp = first . next ;
58+ first . next = second ;
59+ first = temp ;
60+
61+ temp = second . next ;
62+ second . next = first ;
63+ second = temp ;
64+ }
65+ } ;
66+
67+ // TC: O(n)
68+ // SC: O(1)
You can’t perform that action at this time.
0 commit comments