forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwogha95.js
56 lines (51 loc) ยท 1.38 KB
/
wogha95.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
/**
* TC: O(N)
* 1๋ฒ์์ ์ ๋ฐ ๊ธธ์ด๋งํผ ์ํ
* 2๋ฒ์์ ์ ๋ฐ ๊ธธ์ด๋งํผ ์ํ
* 3๋ฒ์์ ์ ๋ฐ ๊ธธ์ด๋งํผ ์ํ
*
* SC: O(1)
* linked list์ node๋ฅผ ๊ฐ๋ฆฌํค๋ ํฌ์ธํฐ๋ฅผ ๊ฐ์ง๊ณ ํ์ฉํ๋ฏ๋ก linked list์ ๊ธธ์ด์ ๋ฌด๊ดํ ๊ณต๊ฐ ๋ณต์ก๋๋ฅผ ๊ฐ์ต๋๋ค.
*
* N: linked list length
*/
/**
* 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) {
// 1. linked list ์ ๋ฐ ์์น ๊ตฌํ๊ธฐ
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
// 2. ํ๋ฐ linked list ์์ ๋ค์ง๊ธฐ
let halfStartTemp = slow.next;
let halfStart = null;
// ์ ๋ฐ์ ๊ธฐ์ค์ผ๋ก linked list ๋๊ธฐ
slow.next = null;
while (halfStartTemp) {
const temp = halfStartTemp.next;
halfStartTemp.next = halfStart;
halfStart = halfStartTemp;
halfStartTemp = temp;
}
// 3. ๋ ๋ฆฌ์คํธ ํฉ์น๊ธฐ
while (head && halfStart) {
const headTemp = head.next;
const halfStartTemp = halfStart.next;
head.next = halfStart;
halfStart.next = headTemp;
head = headTemp;
halfStart = halfStartTemp;
}
};