-
Notifications
You must be signed in to change notification settings - Fork 20
/
LinkedListCycle.kt
43 lines (39 loc) · 957 Bytes
/
LinkedListCycle.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
/**
* Given a linked list, determine if it has a cycle in it.
*
* Follow up:
* Can you solve it without using extra space?
*/
class LinkedListCycle {
// Waiting to be judged.
fun hasCycle(head: ListNode?): Boolean {
if (head?.next == null) {
return false
}
var node = head.next
while (node != head) {
if (node == null) {
return false
}
node = node.next
}
return true
}
// Waiting to be judged.
/*fun hasCycle(head: ListNode?): Boolean {
var slow = head
var fast = head
while (fast != null && fast.next != null) {
slow = slow?.next
fast = fast.next?.next
if (slow === fast) {
return true
}
}
return false
}*/
data class ListNode(
val `val`: Int,
var next: ListNode? = null
)
}