/** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */
classSolution { fundetectCycle(head: ListNode?): ListNode? { if (head?.next == null || head.next?.next == null) { returnnull } var slow = head.next var fast = head.next?.next while (slow != fast) { slow = slow?.next fast = fast?.next?.next if (slow == null || fast == null) { returnnull } }
var ptr = head while (slow != ptr) { slow = slow?.next ptr = ptr?.next } return ptr } }