在PHP中,可以使用数组来表示链表。每个节点都是一个包含数据和指向下一个节点的指针的关联数组。下面是一个示例代码:
class Node {
public $data;
public $next;
public function __construct($data) {
$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();
这段代码创建了一个链表类LinkedList
和一个节点类Node
。LinkedList
类有一个head
属性,表示链表的头节点。insert
方法用于在链表末尾插入新的节点,display
方法用于显示链表中的所有节点。
使用这个链表类,可以插入任意数量的节点,并使用display
方法来显示链表中的所有节点的数据。
请注意,这只是一种表示链表的方法之一,实际上还有其他方法可以实现链表,如使用对象关联性映射(ORM)库来连接数据库表。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站