Untitled

mail@pastecode.io avatar
unknown
kotlin
2 years ago
628 B
1
Indexable
Never
/**
 * 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 {
        if (head == null) return false

        tailrec fun iterate(fast: ListNode?, lazy: ListNode?): Boolean =
         if (fast == null || lazy == null)
                false
            else if (fast == lazy)
                true
            else
                iterate(fast = fast.next?.next, lazy = lazy.next)   

        return iterate(fast = head.next?.next, lazy = head)
    }
}