Untitled
unknown
kotlin
3 years ago
628 B
8
Indexable
/**
* 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)
}
}Editor is loading...