在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(); // 输出: 1 2 3
在上面的示例中,Node
类表示链表的节点,包含一个数据项和一个指向下一个节点的指针。LinkedList
类表示链表,具有插入和显示链表的方法。在插入方法中,如果链表为空,新节点将成为头节点,否则,将遍历链表直到找到最后一个节点,然后将新节点插入到最后一个节点的后面。在显示方法中,将遍历链表并输出每个节点的数据项。
这只是链表的基本实现示例,你可以根据需要进行扩展和修改。
上一篇:php数组去掉空值的方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站