File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ import io.kotest.matchers.shouldBe
4
+ import org.junit.jupiter.api.Test
5
+
6
+ class `linked- list- cycle` {
7
+
8
+ data class ListNode (var `val `: Int ) {
9
+ var next: ListNode ? = null
10
+ }
11
+
12
+ /* *
13
+ * TC: O(n), SC: O(1)
14
+ */
15
+ fun hasCycle (head : ListNode ? ): Boolean {
16
+ if (head == null ) return false
17
+
18
+ var slow = head
19
+ var fast = head
20
+
21
+ while (fast?.next != null ) {
22
+ slow = slow?.next
23
+ fast = fast.next?.next
24
+
25
+ if (slow == fast) return true
26
+ }
27
+
28
+ return false
29
+ }
30
+
31
+ @Test
32
+ fun `입력받은 노드에 사이클이 존재한다면 참을 반환한다` () {
33
+ val three = ListNode (3 )
34
+ val two = ListNode (2 )
35
+ val zero = ListNode (0 )
36
+ val four = ListNode (4 )
37
+
38
+ three.next = two
39
+ two.next = zero
40
+ zero.next = four
41
+ four.next = two
42
+
43
+ hasCycle(three) shouldBe true
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments