## DEV Community

Christopher Coffee

Posted on

# Leetcode: Linked List Cycle (Kotlin)

This is an easy Leetcode LinkedList question. I will go over my thought process for solving this. For this, we will use Floyd’s Cycle Detection algorithm.

### Brainstorm

1. Define two pointers — slow and fast. Initialize both of them to the head of the linked list.

2. Move the slow pointer one step at a time and the fast pointer two steps at a time.

3. At each step, check if slow and fast pointers are equal. If they are equal at some point, then a cycle exists in the linked list.

4. If the fast pointer reaches the end of the list (i.e., it becomes null), then there is no cycle in the list.

### Solution

``````/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* class ListNode(var `val`: Int) {
*     var next: ListNode? = null
* }
*/

class Solution {

while(fast != null && fast.next != null){
slow = slow?.next
fast = fast?.next?.next

if(slow == fast){
return true
}
}

return false
}
}
``````