题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
<?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return bool布尔型
*/
function hasCycle( $head )
{
// write code here
if($head == null || $head->next == null){
return false;
}
$slow = $head;
$fast = $head;
while($fast != null){
$slow = $slow->next;
$fast = $fast->next;
if($fast != null){
$fast = $fast->next;
}
if($slow == $fast){
return true;
}
}
return false;
}
追赶法,慢指针每次走1步,快指针每次走2步。如果有环快指针一定能追上慢指针,到快指针==null为止

