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.
Linked List Cycle - LeetCode
Brainstorm
Define two pointers — slow and fast. Initialize both of them to the head of the linked list.
Move the slow pointer one step at a time and the fast pointer two steps at a time.
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.
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` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { 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 } }
Top comments (0)