/list.php
class Node
{
public $data;
public $next;
function __construct($data, $next = null)
{
$this->data = $data;
$this->next = $next;
}
}
/index.php
require_once('list.php');
$ari = new Node('Ari');
$malcolm = new Node('Malcolm', $ari);
$pete = new Node('Pete', $malcolm);
$ricky = new Node('Ricky', $pete);
$sean = new Node('Sean', $ricky);
cut($sean, 3);
function cut($head, $levelToCut)
{
$i = 1;
$temp = $head;
while (!empty($temp->next)) {
if ($i == $levelToCut) {
$temp = $temp->next;
}
if($i !== 1) {
$temp = $temp->next;
}
$i++;
}
}
<?php
class Node
{
public $data;
public $next;
function __construct($data, $next = null)
{
$this->data = $data;
$this->next = $next;
}
}
class LinkedList{
public $head = null;
public function push(Node $node){
if($this->head == null){
$this->head = $node;
return $this;
}
$current = $this->head;
while($current->next != null) {
$current = $current->next;
}
$current->next = $node;
return $this;
}
public function cut(int $index){
if($index == 0){
$this->head = $this->head->next;
return $this;
}
$i = 0;
$previous = null;
$current = $this->head;
do {
if($i == $index){
$previous->next = $current->next;
return $this;
}
$previous = $current;
$i++;
}while(($current = $current->next) != null);
throw new Exception('Надо эксепшен что бы out of bounds');
}
public function printList()
{
if(!$this->head){
echo 'empty list'.PHP_EOL;
return $this;
}
$current = $this->head;
echo $current->data.' -> ';
while (($current = $current->next)) {
echo $current->data;
if($current->next) {
echo ' -> ';
}
}
echo PHP_EOL;
return $this;
}
}
$linkedList = new LinkedList();
$linkedList
->push(new Node('Ari'))
->push(new Node('Malcolm'))
->push(new Node('Pete'))
->push(new Node('Ricky'))
->push(new Node('Sean'));
$linkedList
->printList()
->cut(2)
->printList()
->cut(1)
->printList()
->cut(10);