forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdy8739.js
54 lines (41 loc) ยท 1.16 KB
/
jdy8739.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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function (head) {
if (!head) {
return null;
}
const stack = [];
let node = head;
while (node) {
stack.push(node);
node = node.next;
}
const length = stack.length;
node = head;
let count = 0;
while (count < length) {
if (count % 2 === 0) {
const top = stack.pop();
top.next = node.next;
node.next = top;
}
if (count === length - 1) {
node.next = null;
} else {
node = node.next;
}
count++;
}
return head;
};
// ์๊ฐ๋ณต์ก๋ O(n) -> while๋ฌธ์ด ๋งํฌ๋๋ฆฌ์คํธ์ ๊ธธ์ด๋งํผ ์ํ๋ฅผํ๊ธฐ๋๋ฌธ์ ๋งํฌ๋๋ฆฌ์คํธ์ ๊ธธ์ด๋งํผ ์๊ฐ์ด ๊ฑธ๋ฆผ
// ๊ณต๊ฐ๋ณต์ก๋ O(n) -> ์คํ์ ๋ชจ๋ ๋
ธ๋๋ฅผ ์ ์ฅํ๊ธฐ ๋๋ฌธ์ ๋งํฌ๋๋ฆฌ์คํธ์ ๊ธธ์ด๋งํผ ๊ณต๊ฐ์ด ํ์