判断是否是环形链表
给定一个链表,判断该链表是否是环形链表
思路:假如A走了两步,B走了一步,那么判断A的next是否为空.这边需要用到循环
<?php
//环形链表
//直的走两个 有环的走一个 如果走一个的追的上走两个的,那么肯定是环形
class cycle
{
function hasCycle($head) {
$first = $head;//走一步
$throw = $head;//走两步
while($first != null && $throw->next != null){
$first = $first->next->next;
$throw = $throw->next;
if($first === $throw){
return true;
}
}
return false;
}
}