forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEcoFriendlyAppleSu.kt
36 lines (31 loc) ยท 1.16 KB
/
EcoFriendlyAppleSu.kt
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
package leetcode_study
/*
* singly linked list๋ฅผ ์ฌ์ ๋ ฌํ๋ ๋ฌธ์
* ์๊ฐ ๋ณต์ก๋: O(n)
* -> ์ ์ฒด ๋
ธ๋๋ฅผ ์ ์ฅํ๊ธฐ ์ํด ์ํํ๋ ๊ณผ์ O(n)
* -> ๋ฆฌ์คํธ์ ์๊ณผ ๋ค์ ํฌ์ธํฐ๋ฅผ ๋๊ณ ์ฃผ์๊ฐ์ ๋ณ๊ฒฝํ๋ ๊ณผ์ O(log n)
* ๊ณต๊ฐ ๋ณต์ก๋: O(n)
* -> ๋
ธ๋ ์ ์ฒด๋ฅผ ๋ด์ ์๋ก์ด list ํ์ O(n)
* */
fun reorderList(head: ListNode?): Unit {
val tempNodeList = mutableListOf<ListNode>()
var currentNode = head
while (currentNode != null) {
tempNodeList.add(currentNode)
currentNode = currentNode.next
}
// ์์ชฝ ๋์์๋ถํฐ ๊ต์ฐจ๋ก ์ฐ๊ฒฐ
var i = 0
var j = tempNodeList.size - 1
while (i < j) {
// ๋จผ์ ์์ชฝ ๋
ธ๋์ next๊ฐ ๋ค์ชฝ ๋
ธ๋๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ํจ
tempNodeList[i].next = tempNodeList[j]
i++ // ๋ค์ ์์ชฝ ๋
ธ๋ ์ ํ
// ๋ง์ฝ ์์ชฝ๊ณผ ๋ค์ชฝ์ด ๋ง๋ ๊ฒฝ์ฐ (์ง์๊ฐ์ผ ๋), ๋ฐ๋ณต ์ข
๋ฃ
if (i == j) break
// ๋ค์ชฝ ๋
ธ๋์ next๊ฐ ์๋ก์ด ์์ชฝ ๋
ธ๋๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ํจ
tempNodeList[j].next = tempNodeList[i]
j-- // ๋ค์ ๋ค์ชฝ ๋
ธ๋ ์ ํ
}
tempNodeList[i].next = null
}