Skip to content

Commit b830d52

Browse files
committed
Add Linked List Loop solutions
1 parent 7230456 commit b830d52

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/*
2+
Definition of ListNode:
3+
data class ListNode(var value: Int, var next: ListNode? = null)
4+
*/
5+
6+
fun linkedListLoop(head: ListNode?): Boolean {
7+
var slow = head
8+
var fast = head
9+
// Check both 'fast' and 'fast.next' to avoid null pointer
10+
// exceptions when we perform 'fast.next' and 'fast.next.next'.
11+
while (fast != null && fast.next != null) {
12+
slow = slow!!.next
13+
fast = fast.next!!.next
14+
if (fast == slow) {
15+
return true
16+
}
17+
}
18+
return false
19+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/*
2+
Definition of ListNode:
3+
data class ListNode(var value: Int, var next: ListNode? = null)
4+
*/
5+
6+
fun linkedListLoopNaive(head: ListNode?): Boolean {
7+
val visited = mutableSetOf<ListNode>()
8+
var curr = head
9+
while (curr != null) {
10+
// Cycle detected if the current node has already been visited.
11+
if (visited.contains(curr)) {
12+
return true
13+
}
14+
visited.add(curr)
15+
curr = curr.next
16+
}
17+
return false
18+
}

0 commit comments

Comments
 (0)