142. Linked List Cycle II
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
class Solution {
/**
* @param ListNode $head
* @return ListNode
*/
function detectCycle($head) {
$fast = $head;
$slow = $head;
$step = 0;
while ($fast && $fast->next) {
++$step;
$slow = $slow->next;
$fast = $fast->next->next;
if ($slow == $fast) {
$slow = $head;
while($slow != $fast) {
$slow = $slow->next;
$fast = $fast->next;
}
return $slow;
}
}
return null;
}
}
Last updated