forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdalma.kt
98 lines (85 loc) ยท 2.59 KB
/
jdalma.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class `reorder-list` {
fun reorderList(root: ListNode?) {
if (root == null) return
usingTwoPointers(root)
}
/**
* TC: O(n), SC: O(n)
*/
private fun usingStack(input: ListNode) {
val tail = ArrayDeque<ListNode>().apply {
var node: ListNode? = input
while (node != null) {
this.add(node)
node = node.next
}
}
val dummy = ListNode(-1)
var node: ListNode = dummy
var head: ListNode = input
for (i in 0 until tail.size) {
if (i % 2 != 0) {
node.next = tail.removeLast()
} else {
node.next = head
head.next?.let { head = it }
}
node.next?.let { node = it }
}
node.next = null
}
/**
* TC: O(n), SC: O(1)
*/
private fun usingTwoPointers(input: ListNode) {
if (input.next == null) return
var slow: ListNode? = input
var fast: ListNode? = input
while (fast?.next != null && fast.next?.next != null) {
slow = slow?.next
fast = fast.next?.next
}
val firstHalfEnd = slow
var secondHalfStart = slow?.next
firstHalfEnd?.next = null
secondHalfStart = reverse(secondHalfStart)
var node1: ListNode? = input
var node2: ListNode? = secondHalfStart
while (node2 != null) {
val (next1, next2) = (node1?.next to node2?.next)
node1?.next = node2
node2.next = next1
node1 = next1
node2 = next2
}
}
private fun reverse(head: ListNode?): ListNode? {
var prev: ListNode? = null
var current = head
while (current != null) {
val next = current.next
current.next = prev
prev = current
current = next
}
return prev
}
@Test
fun `์ ๋ ฌ๋ ๋ฆฌ์คํธ ๋
ธ๋์ ์ฐธ์กฐ ์ฒด์ด๋์ ํน์ ์์๋ก ์ฌ์ ๋ ฌํ๋ค`() {
val actual = ListNode.of(1,2,3,4,5).apply {
reorderList(this)
}
actual.`val` shouldBe 1
actual.next!!.`val` shouldBe 5
actual.next!!.next!!.`val` shouldBe 2
actual.next!!.next!!.next!!.`val` shouldBe 4
actual.next!!.next!!.next!!.next!!.`val` shouldBe 3
actual.next!!.next!!.next!!.next!!.next shouldBe null
ListNode.of(1,2,3,4,5,6).apply {
reorderList(this)
}
}
}