forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnhistory.js
68 lines (61 loc) ยท 1.44 KB
/
nhistory.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// First option : change node value
var reorderList = function (head) {
if (!head) return;
// Create new arr to return result and current head
let arr = [];
let curr = head;
// Make list array that has every values from linked list
let list = [];
while (curr) {
list.push(curr.val);
curr = curr.next;
}
// Iterate list array if i%2 === 0 then curr.val = list[Math.floor(i / 2)]
// If i%2 !== 0 them curr.val = list[list.length - Math.floor((i + 1) / 2)]
curr = head;
for (let i = 0; i < list.length; i++) {
if (i % 2 === 0) {
curr.val = list[Math.floor(i / 2)];
} else {
curr.val = list[list.length - Math.floor((i + 1) / 2)];
}
curr = curr.next;
}
};
// TC: O(n)
// SC: O(n)
// Second option : move node without changing values
var reorderList = function (head) {
// Edge case
if (!head) return;
// Find mid node from linked list
let slow = head,
fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse second half list
let prev = null,
curr = slow,
temp;
while (curr) {
temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
// Modify linked list as followed instruction
let first = head,
second = prev;
while (second.next) {
temp = first.next;
first.next = second;
first = temp;
temp = second.next;
second.next = first;
second = temp;
}
};
// TC: O(n)
// SC: O(1)