Skip to content

Commit d66f7a0

Browse files
committed
reorder list solution
1 parent 85f6c91 commit d66f7a0

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

reorder-list/byol-han.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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 || !head.next) return;
14+
15+
// 1. 중간 지점 찾기 (slow, fast 포인터 사용)
16+
let slow = head;
17+
let fast = head;
18+
while (fast.next && fast.next.next) {
19+
slow = slow.next;
20+
fast = fast.next.next;
21+
}
22+
23+
// 2. 중간 이후 리스트 뒤집기
24+
let prev = null;
25+
let curr = slow.next;
26+
while (curr) {
27+
let nextTemp = curr.next;
28+
curr.next = prev;
29+
prev = curr;
30+
curr = nextTemp;
31+
}
32+
// 중간 지점 이후는 끊기
33+
slow.next = null;
34+
35+
// 3. 앞쪽 리스트와 뒤쪽 리스트 교차 병합
36+
let first = head;
37+
let second = prev;
38+
while (second) {
39+
let tmp1 = first.next;
40+
let tmp2 = second.next;
41+
42+
first.next = second;
43+
second.next = tmp1;
44+
45+
first = tmp1;
46+
second = tmp2;
47+
}
48+
};

0 commit comments

Comments
 (0)