php如何实现链表
PHP 实现链表的基本方法
链表是一种线性数据结构,由节点组成,每个节点包含数据和指向下一个节点的指针。在 PHP 中,可以通过类来实现链表。
定义节点类
节点类是链表的基本单元,包含数据(data)和指向下一个节点的指针(next)。
class Node {
public $data;
public $next;
public function __construct($data) {
$this->data = $data;
$this->next = null;
}
}
定义链表类
链表类提供对链表的操作,如插入、删除、遍历等。
class LinkedList {
public $head;
public function __construct() {
$this->head = null;
}
// 在链表头部插入节点
public function insertAtHead($data) {
$newNode = new Node($data);
$newNode->next = $this->head;
$this->head = $newNode;
}
// 在链表尾部插入节点
public function insertAtTail($data) {
$newNode = new Node($data);
if ($this->head === null) {
$this->head = $newNode;
return;
}
$current = $this->head;
while ($current->next !== null) {
$current = $current->next;
}
$current->next = $newNode;
}
// 删除指定数据的节点
public function deleteNode($data) {
if ($this->head === null) {
return;
}
if ($this->head->data === $data) {
$this->head = $this->head->next;
return;
}
$current = $this->head;
while ($current->next !== null && $current->next->data !== $data) {
$current = $current->next;
}
if ($current->next !== null) {
$current->next = $current->next->next;
}
}
// 遍历链表并打印数据
public function printList() {
$current = $this->head;
while ($current !== null) {
echo $current->data . " ";
$current = $current->next;
}
echo "\n";
}
}
使用链表
以下是创建链表、插入节点、删除节点和打印链表的示例。
$list = new LinkedList();
$list->insertAtHead(10);
$list->insertAtHead(20);
$list->insertAtTail(30);
$list->printList(); // 输出: 20 10 30
$list->deleteNode(10);
$list->printList(); // 输出: 20 30
链表的其他操作
可以根据需求扩展链表的功能,例如查找节点、反转链表等。
查找节点
检查链表中是否存在某个值。
public function search($data) {
$current = $this->head;
while ($current !== null) {
if ($current->data === $data) {
return true;
}
$current = $current->next;
}
return false;
}
反转链表
将链表的节点顺序反转。
public function reverse() {
$prev = null;
$current = $this->head;
while ($current !== null) {
$next = $current->next;
$current->next = $prev;
$prev = $current;
$current = $next;
}
$this->head = $prev;
}
链表的应用场景
链表适用于动态数据存储,频繁插入和删除操作的场景。与数组相比,链表在插入和删除时更高效,但访问元素时需要遍历。







