链接列表是计算机科学中的基本数据结构,其中元素(称为节点)通过指针顺序连接。与数组不同,链接列表是动态的,这意味着它们可以在不需要调整操作大小的情况下生长或收缩。在本教程中,我们将介绍实现php中的链接列表的基础。
链接列表节点的结构>
链接列表中的每个节点都由两个部分组成:
class node { public $data; public $next; public function __construct($data) { $this->data = $data; $this->next = null; } }
为了管理节点,我们创建了一个链接列表类,该类别维护列表的头部并提供对其进行操作的方法。
基本操作
1。将节点添加到结尾
我们通过通过节点迭代直到到达最后一个来添加一个节点。
199862226633
2。显示列表
>
public function display() {
$current = $this->head;
while ($current !== null) {
echo $current->data . " -> ";
$current = $current->next;
}
echo "null\n";
}
3。删除节点
public function delete($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; } }
$linkedlist = new linkedlist(); $linkedlist->append(10); $linkedlist->append(20); $linkedlist->append(30); echo "initial list:\n"; $linkedlist->display(); $linkedlist->delete(20); echo "after deleting 20:\n"; $linkedlist->display();
Initial List: 10 -> 20 -> 30 -> NULL After Deleting 20: 10 -> 30 -> NULL
以上就是PHP 中的链接列表简介:初学者指南的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号