- Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
- bool(false) bool(true)
<?php
function hasLoop($head) {
$slow = $head;
$fast = $head;
while ($fast !== null && $fast->next !== null) {
$slow = $slow->next;
$fast = $fast->next->next;
if ($slow === $fast) {
return true;
}
}
return false;
}
// example usage
class Node {
public $data;
public $next;
public function __construct($data) {
$this->data = $data;
$this->next = null;
}
}
$a = new Node(1);
$b = new Node(2);
$c = new Node(3);
$d = new Node(4);
$a->next = $b;
$b->next = $c;
$c->next = $d;
var_dump(hasLoop($a)); // false
$d->next = $b;
var_dump(hasLoop($a)); // true