-
Notifications
You must be signed in to change notification settings - Fork 17
/
HasCycle.kt
41 lines (35 loc) · 1016 Bytes
/
HasCycle.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
package com.daily.algothrim.leetcode
import com.daily.algothrim.linked.LinkedNode
/**
* 环形链表(leetcode 141)
*/
class HasCycle {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val head = LinkedNode(1)
val cycleNode = LinkedNode(2)
println(HasCycle().hasCycle(head.apply {
next = cycleNode.apply {
next = LinkedNode(3).apply {
next = LinkedNode(2).apply {
next = LinkedNode(1).apply {
next = cycleNode
}
}
}
}
}))
}
}
fun hasCycle(head: LinkedNode<Int>?): Boolean {
var fast = head
var slow = head
while (fast?.next != null) {
fast = fast.next?.next
slow = slow?.next
if (slow == fast) return true
}
return false
}
}