problem: 142. Linked List Cycle II
language: php
code:
/**
* 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) {
if($head == null || $head->next == null) return null;
$fast = $head;
$slow = $head;
while ($fast != null && $fast->next != null) {
$fast = $fast->next->next;
$slow = $slow->next;
if ($fast === $slow) {
break;
}
}
$ptr = $head;
while ($ptr !== $slow) {
$ptr = $ptr->next;
$slow = $slow->next;
}
return $ptr;
}
}I've tried many different code, but unfortunatly all of them shows Nesting level too deep - recursive dependency error.