Skip to content

Commit 00cd79b

Browse files
committed
2. reorder-list
1 parent cbf5a21 commit 00cd79b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

reorder-list/sunjae95.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @description
3+
* 인덱스로 접근하지 못하는 구조를 인덱스로 접근하게 하여 two pointer로 풀이
4+
*
5+
* n = total node count
6+
* time complexity: O(n)
7+
* space complexity: O(n)
8+
*/
9+
var reorderList = function (head) {
10+
// convert from queue to list
11+
let travelNode = head;
12+
const list = [];
13+
while (travelNode) {
14+
list.push(travelNode);
15+
travelNode = travelNode.next;
16+
}
17+
// two pointer
18+
let [left, right] = [0, list.length - 1];
19+
const node = new ListNode();
20+
let tail = node;
21+
22+
while (left <= right) {
23+
// 1. left append
24+
const leftNode = list[left];
25+
leftNode.next = null;
26+
tail.next = leftNode;
27+
tail = leftNode;
28+
// 2. conditional right append
29+
const rightNode = list[right];
30+
rightNode.next = null;
31+
if (left !== right) {
32+
tail.next = rightNode;
33+
tail = rightNode;
34+
}
35+
36+
left++;
37+
right--;
38+
}
39+
40+
head = node.next;
41+
};

0 commit comments

Comments
 (0)