|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | + |
| 6 | +class `remove-nth-node-from-end-of-list` { |
| 7 | + |
| 8 | + fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { |
| 9 | + if (head == null || (head.next == null && n == 1)) { |
| 10 | + return null |
| 11 | + } |
| 12 | + return usingTwoPointers(head, n) |
| 13 | + } |
| 14 | + |
| 15 | + /** |
| 16 | + * TC: O(n), SC: O(n) |
| 17 | + */ |
| 18 | + private fun usingExtraList(head: ListNode, n: Int): ListNode { |
| 19 | + |
| 20 | + fun toList(node: ListNode): List<ListNode> { |
| 21 | + val list = mutableListOf<ListNode>() |
| 22 | + var tmp: ListNode? = node |
| 23 | + while (tmp != null) { |
| 24 | + list.add(tmp) |
| 25 | + tmp = tmp.next |
| 26 | + } |
| 27 | + return list |
| 28 | + } |
| 29 | + |
| 30 | + val list = toList(head) |
| 31 | + var root = head |
| 32 | + if (list.size == n) { |
| 33 | + root = list[1] |
| 34 | + } else { |
| 35 | + list[list.size - n - 1].next = list[list.size - n].next |
| 36 | + } |
| 37 | + return root |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * fast를 n만큼 먼저 이동 시킨 후 fast.next가 null일 때까지 fast와 slow를 다음 노드로 이동시킨다. |
| 42 | + * fast를 n만큼 이동시키면 결국 slow는 n의 이전 노드에 도달하게 되기에 해당 slow 노드의 next를 변경하면 된다. |
| 43 | + * TC: O(n), SC: O(1) |
| 44 | + */ |
| 45 | + private fun usingTwoPointers(head: ListNode, n: Int): ListNode? { |
| 46 | + var fast: ListNode? = head |
| 47 | + var slow: ListNode? = head |
| 48 | + |
| 49 | + repeat(n) { |
| 50 | + fast = fast?.next |
| 51 | + } |
| 52 | + if (fast == null) return head.next |
| 53 | + |
| 54 | + while (fast?.next != null) { |
| 55 | + fast = fast?.next |
| 56 | + slow = slow?.next |
| 57 | + } |
| 58 | + slow?.next = slow?.next?.next |
| 59 | + return head |
| 60 | + } |
| 61 | + |
| 62 | + @Test |
| 63 | + fun `링크된 목록의 헤드가 주어지면 목록의 끝에서 n번째 노드를 제거하고 그 헤드를 반환합니다`() { |
| 64 | + removeNthFromEnd(ListNode.of(1), 1).also { |
| 65 | + it shouldBe null |
| 66 | + } |
| 67 | + |
| 68 | + removeNthFromEnd(ListNode.of(1, 2), 2).also { |
| 69 | + it shouldBe ListNode(2) |
| 70 | + } |
| 71 | + |
| 72 | + removeNthFromEnd(ListNode.of(1, 2), 1)!!.also { |
| 73 | + it shouldBe ListNode(1) |
| 74 | + it.next shouldBe null |
| 75 | + } |
| 76 | + |
| 77 | + removeNthFromEnd(ListNode.of(1, 2, 3, 4, 5), 2)!!.also { |
| 78 | + it.next!!.next!!.`val` shouldBe 3 |
| 79 | + it.next!!.next!!.next!!.`val` shouldBe 5 |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments