Skip to content

Commit 694eba9

Browse files
author
แ„‹แ…ตแ„‹แ…งแ†ซแ„‰แ…ฎ
committed
reorder list
1 parent 8a4d98e commit 694eba9

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package leetcode_study
2+
3+
/*
4+
* singly linked list๋ฅผ ์žฌ์ •๋ ฌํ•˜๋Š” ๋ฌธ์ œ
5+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
6+
* -> ์ „์ฒด ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด ์ˆœํ™˜ํ•˜๋Š” ๊ณผ์ • O(n)
7+
* -> ๋ฆฌ์ŠคํŠธ์˜ ์•ž๊ณผ ๋’ค์— ํฌ์ธํ„ฐ๋ฅผ ๋‘๊ณ  ์ฃผ์†Œ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๋Š” ๊ณผ์ • O(log n)
8+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
9+
* -> ๋…ธ๋“œ ์ „์ฒด๋ฅผ ๋‹ด์„ ์ƒˆ๋กœ์šด list ํ•„์š” O(n)
10+
* */
11+
fun reorderList(head: ListNode?): Unit {
12+
val tempNodeList = mutableListOf<ListNode>()
13+
var currentNode = head
14+
15+
while (currentNode != null) {
16+
tempNodeList.add(currentNode)
17+
currentNode = currentNode.next
18+
}
19+
20+
// ์–‘์ชฝ ๋์—์„œ๋ถ€ํ„ฐ ๊ต์ฐจ๋กœ ์—ฐ๊ฒฐ
21+
var i = 0
22+
var j = tempNodeList.size - 1
23+
while (i < j) {
24+
// ๋จผ์ € ์•ž์ชฝ ๋…ธ๋“œ์˜ next๊ฐ€ ๋’ค์ชฝ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ํ•จ
25+
tempNodeList[i].next = tempNodeList[j]
26+
i++ // ๋‹ค์Œ ์•ž์ชฝ ๋…ธ๋“œ ์„ ํƒ
27+
28+
// ๋งŒ์•ฝ ์•ž์ชฝ๊ณผ ๋’ค์ชฝ์ด ๋งŒ๋‚œ ๊ฒฝ์šฐ (์ง์ˆ˜๊ฐœ์ผ ๋•Œ), ๋ฐ˜๋ณต ์ข…๋ฃŒ
29+
if (i == j) break
30+
31+
// ๋’ค์ชฝ ๋…ธ๋“œ์˜ next๊ฐ€ ์ƒˆ๋กœ์šด ์•ž์ชฝ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ํ•จ
32+
tempNodeList[j].next = tempNodeList[i]
33+
j-- // ๋‹ค์Œ ๋’ค์ชฝ ๋…ธ๋“œ ์„ ํƒ
34+
}
35+
tempNodeList[i].next = null
36+
}

0 commit comments

Comments
ย (0)