-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedListCycle.kt
98 lines (85 loc) · 2.48 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package problems
class LinkedListCycle {
class ListNode(var `val` : Int) {
var next: ListNode? = null
}
//LinkedListCycle I - Easy
class ChpaterOne {
//Floyd's Tortoise And Hare
fun hasCycle(head: ListNode?): Boolean {
if (head == null) {
return false
}
var slow = head
var fast = head.next
while (slow != fast) {
if (fast == null || fast.next == null) {
return false
}
slow = slow?.next
fast = fast.next?.next
}
return true
}
//Visit Remnant
fun hasCycles(head: ListNode?): Boolean {
var node = head
while(node != null) {
if (node.`val` == Integer.MIN_VALUE) {
return true
} else {
node.`val` = Integer.MIN_VALUE
node = node.next
}
}
return false
}
//HashTable
fun hasCycled(head: ListNode?): Boolean {
val nodeSet : MutableSet<ListNode> = hashSetOf()
var node = head
while(node != null) {
if (nodeSet.contains(node)) {
return true
} else {
nodeSet.add(node)
node = node.next
}
}
return false
}
}
//LinkedListCycle II - Medium
class ChapterTwo {
fun hasCycle(head: ListNode?): Boolean {
if (head == null) {
return false
}
var slow = head
var fast = head.next
while (slow != fast) {
//if slow meets end first no loop
//if fast meets end first loop
if (fast == null || fast.next == null) {
return false
}
slow = slow?.next
fast = fast.next?.next
}
return true
}
//Visit Remnant
fun detectCycle(head: ListNode?): ListNode? {
var node = head
while(node != null) {
if (node.`val` == Integer.MIN_VALUE) {
return node
} else {
node.`val` = Integer.MIN_VALUE
node = node.next
}
}
return null
}
}
}