Напиши функцию на php, которая сможет обнаружить наличие петли (т.е. зацикливание) в односвязном списке , либо отсутствие петель.
Решение ( live ):
<?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

Нет Ответов