Skip to content

Commit cc30fce

Browse files
committed
Modified reorder list solution
1 parent bd9fcbf commit cc30fce

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

reorder-list/nhistory.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// First option : change node value
12
var 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)

0 commit comments

Comments
 (0)