在PHP中,可以使用数组来实现链表的基本功能。下面是一个简单的示例代码:
class Node {
public $data;
public $next;
public function __construct($data = null) {
$this->data = $data;
$this->next = null;
}
}
class LinkedList {
private $head;
public function __construct() {
$this->head = null;
}
public function insert($data) {
$newNode = new Node($data);
if ($this->head === null) {
$this->head = $newNode;
} else {
$current = $this->head;
while ($current->next !== null) {
$current = $current->next;
}
$current->next = $newNode;
}
}
public function display() {
$current = $this->head;
while ($current !== null) {
echo $current->data . " ";
$current = $current->next;
}
}
}
// 创建一个链表对象
$linkedList = new LinkedList();
// 插入数据
$linkedList->insert(1);
$linkedList->insert(2);
$linkedList->insert(3);
// 显示链表内容
$linkedList->display();
运行上述代码,将输出:1 2 3,表示链表中的数据。这是一个简单的链表实现,可以根据需要扩展其他功能,如删除节点、查找节点等。
上一篇:php 加号换成2b
下一篇:liuxn配置php环境
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站