php实现简单链表
链表的定义
链表由两个块构成,data和next,data代表链表的值,next代表下一个值的指针
节点类 Node.php
<?php
/**
* 链表节点类
*/
class Node
{
/**
* 链表的数据
*
* @var mixed
*/
public $data;
/**
* 链表的下一层
*
* @var Node
*/
public $next;
/**
* 初始化链表
*
* @param mixed $data
*/
public function __construct($data)
{
$this->data = $data;
$this->next = null;
}
}
链表实现类 LinkedList.php
<?php
require __DIR__ . '/Node.php';
/**
* 链表实现
*/
class LinkedList
{
/**
* 链表数据
* @var Node
*/
private $data;
/**
* 添加链表数据
* @param mixed $data
* @return LinkedList
*/
public function append($data): LinkedList
{
$node = new Node($data);
//数据为空,代表第一次创建
if($this->data === null){
$this->data = $node;
}else{
//获取当前的所有节点
$current = $this->data;
//循环节点。如果节点下级不为空,则继续寻找
while($current->next !== null){
//每次都赋值节点下级,直到找到下级为空的节点,此时 $current 为最后一层
$current = $current->next;
}
//把最后一层设置为node
$current->next = $node;
}
return $this;
}
/**
* 给头部追加链表
* @param mixed $data
* @return LinkedList
*/
public function prepend($data): LinkedList
{
//创建一个新的节点
$node = new Node($data);
//节点的下级是当前的所有节点
$node->next = $this->data;
//把链表设置为新创建的node
$this->data = $node;
return $this;
}
/**
* 删除链表内某个值
* @param mixed $data
* @return LinkedList
*/
public function delete($data): LinkedList
{
//只有链表不为空才进行处理
if($this->data instanceof Node){
//如果链表只有一层
if($this->data->next === null){
//只有一层且数据相同
if($this->data->data === $data){
$this->data = null;
}
}else{
//获取到当前节点
$current = $this->data;
//循环,看当前节点的值是否等于给定的值
while($current->data !== $data){
//如果当前节点的值不等于给定的值,那么查看下一个节点是否等于给定的值
if($current->next->data === $data){
//如果下一个节点的值等于给定的值,就把当前节点的下级更改为下级的下级
$current->next = $current->next->next;
break;
}
//如果当前节点的值不等于给定的值,且下级节点的值也不等于给定值,则用下一个节点进行循环
$current = $current->next;
}
$current = $current->next;
}
}
return $this;
}
/**
* 打印整个链表
* @param mixed $data
* @return void
*/
public function printList(): void
{
$string = "";
$current = $this->data;
while($current->next !== null){
$string .= "节点值: [ ". $current->data ." ]" . PHP_EOL;//可替换为<br>
$current = $current->next;
}
//最后一个节点的next为null,需要单独处理
$string .= "节点值: [ ". $current->data ." ]". PHP_EOL; // 最后一个节点不用加PHP_EOL
echo $string;
}
}
$list = new LinkedList();
$list->append(1)->append(2)->append(3)->prepend(0)->printList();
php实现简单链表
https://lysowc.cn/archives/1733292517976