|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | + |
| 6 | +class `reorder-list` { |
| 7 | + |
| 8 | + fun reorderList(root: ListNode?) { |
| 9 | + if (root == null) return |
| 10 | + usingTwoPointers(root) |
| 11 | + } |
| 12 | + |
| 13 | + /** |
| 14 | + * TC: O(n), SC: O(n) |
| 15 | + */ |
| 16 | + private fun usingStack(input: ListNode) { |
| 17 | + val tail = ArrayDeque<ListNode>().apply { |
| 18 | + var node: ListNode? = input |
| 19 | + while (node != null) { |
| 20 | + this.add(node) |
| 21 | + node = node.next |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + val dummy = ListNode(-1) |
| 26 | + var node: ListNode = dummy |
| 27 | + var head: ListNode = input |
| 28 | + for (i in 0 until tail.size) { |
| 29 | + if (i % 2 != 0) { |
| 30 | + node.next = tail.removeLast() |
| 31 | + } else { |
| 32 | + node.next = head |
| 33 | + head.next?.let { head = it } |
| 34 | + } |
| 35 | + node.next?.let { node = it } |
| 36 | + } |
| 37 | + node.next = null |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * TC: O(n), SC: O(1) |
| 42 | + */ |
| 43 | + private fun usingTwoPointers(input: ListNode) { |
| 44 | + if (input.next == null) return |
| 45 | + |
| 46 | + var slow: ListNode? = input |
| 47 | + var fast: ListNode? = input |
| 48 | + while (fast?.next != null && fast.next?.next != null) { |
| 49 | + slow = slow?.next |
| 50 | + fast = fast.next?.next |
| 51 | + } |
| 52 | + |
| 53 | + val firstHalfEnd = slow |
| 54 | + var secondHalfStart = slow?.next |
| 55 | + firstHalfEnd?.next = null |
| 56 | + |
| 57 | + secondHalfStart = reverse(secondHalfStart) |
| 58 | + |
| 59 | + var node1: ListNode? = input |
| 60 | + var node2: ListNode? = secondHalfStart |
| 61 | + while (node2 != null) { |
| 62 | + val (next1, next2) = (node1?.next to node2?.next) |
| 63 | + node1?.next = node2 |
| 64 | + node2.next = next1 |
| 65 | + node1 = next1 |
| 66 | + node2 = next2 |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private fun reverse(head: ListNode?): ListNode? { |
| 71 | + var prev: ListNode? = null |
| 72 | + var current = head |
| 73 | + while (current != null) { |
| 74 | + val next = current.next |
| 75 | + current.next = prev |
| 76 | + prev = current |
| 77 | + current = next |
| 78 | + } |
| 79 | + return prev |
| 80 | + } |
| 81 | + |
| 82 | + @Test |
| 83 | + fun `정렬된 리스트 노드의 참조 체이닝을 특정 순서로 재정렬한다`() { |
| 84 | + val actual = ListNode.of(1,2,3,4,5).apply { |
| 85 | + reorderList(this) |
| 86 | + } |
| 87 | + actual.`val` shouldBe 1 |
| 88 | + actual.next!!.`val` shouldBe 5 |
| 89 | + actual.next!!.next!!.`val` shouldBe 2 |
| 90 | + actual.next!!.next!!.next!!.`val` shouldBe 4 |
| 91 | + actual.next!!.next!!.next!!.next!!.`val` shouldBe 3 |
| 92 | + actual.next!!.next!!.next!!.next!!.next shouldBe null |
| 93 | + |
| 94 | + ListNode.of(1,2,3,4,5,6).apply { |
| 95 | + reorderList(this) |
| 96 | + } |
| 97 | + } |
| 98 | +} |
0 commit comments