Skip to content

Commit 59e8ed2

Browse files
committed
reorder-list solution
1 parent a828b56 commit 59e8ed2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

reorder-list/jdy8739.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {void} Do not return anything, modify head in-place instead.
11+
*/
12+
var reorderList = function (head) {
13+
if (!head) {
14+
return null;
15+
}
16+
17+
const stack = [];
18+
19+
let node = head;
20+
21+
while (node) {
22+
stack.push(node);
23+
node = node.next;
24+
}
25+
26+
const length = stack.length;
27+
28+
node = head;
29+
let count = 0;
30+
31+
while (count < length) {
32+
if (count % 2 === 0) {
33+
const top = stack.pop();
34+
35+
top.next = node.next;
36+
37+
node.next = top;
38+
}
39+
40+
if (count === length - 1) {
41+
node.next = null;
42+
} else {
43+
node = node.next;
44+
}
45+
46+
count++;
47+
}
48+
49+
50+
return head;
51+
};
52+
53+
// 시간복잡도 O(n) -> while문이 링크드리스트의 길이만큼 순회를하기때문에 링크드리스트의 길이만큼 시간이 걸림
54+
// 공간복잡도 O(n) -> 스택에 모든 노드를 저장하기 때문에 링크드리스트의 길이만큼 공간이 필요

0 commit comments

Comments
 (0)