当前位置:首页 > PHP

php 实现单链表

2026-01-14 12:55:08PHP

单链表的基本概念

单链表是一种线性数据结构,由节点组成,每个节点包含数据域和指向下一个节点的指针域。链表的头节点是访问整个链表的入口。

php 实现单链表

单链表的节点类实现

在PHP中,可以通过类来定义链表节点。每个节点包含数据(data)和指向下一个节点的指针(next)。

php 实现单链表

class ListNode {
    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 insertAtHead($data) {
        $newNode = new ListNode($data);
        $newNode->next = $this->head;
        $this->head = $newNode;
    }

    // 在链表尾部插入节点
    public function insertAtTail($data) {
        $newNode = new ListNode($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 "NULL\n";
    }
}

使用示例

以下是如何使用上述单链表类的示例代码:

$list = new LinkedList();
$list->insertAtHead(10);
$list->insertAtHead(20);
$list->insertAtTail(30);
$list->printList(); // 输出: 20 -> 10 -> 30 -> NULL

$list->deleteNode(10);
$list->printList(); // 输出: 20 -> 30 -> NULL

注意事项

  • 链表的操作需要注意空指针问题,尤其是在删除和插入节点时。
  • 链表的时间复杂度:插入和删除操作在头部为O(1),在尾部为O(n);查找操作为O(n)。
  • 链表适用于频繁插入和删除的场景,但随机访问效率较低。

通过上述实现,可以完成单链表的基本操作。根据实际需求,可以进一步扩展功能,如反转链表、检测环等。

标签: 链表php
分享给朋友:

相关文章

php实现过程

php实现过程

PHP 实现过程 PHP 是一种广泛使用的服务器端脚本语言,特别适合 Web 开发。以下是 PHP 实现过程的关键步骤和注意事项。 安装与配置 下载并安装 PHP,可以从官方 PHP 网站获取最新版…

php数据库实现

php数据库实现

PHP 连接 MySQL 数据库 使用 mysqli 扩展连接 MySQL 数据库: <?php $servername = "localhost"; $username = "usernam…

php实现评论功能

php实现评论功能

数据库设计 创建评论表(示例结构): CREATE TABLE `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id`…

php redis 队列实现

php redis 队列实现

PHP Redis 队列实现 Redis 是一个高性能的键值存储系统,常被用作消息队列。以下是使用 PHP 和 Redis 实现队列的几种方法。 安装依赖 确保已安装 PHP Redis 扩展。可以…

php实现单例模式

php实现单例模式

单例模式的概念 单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供一个全局访问点。这种模式常用于数据库连接、日志记录器等需要全局唯一实例的场景。 PHP实现单例模式的关键步骤 私有化构造函…

php 插件实现

php 插件实现

PHP 插件实现方法 PHP 插件可以通过多种方式实现,具体取决于插件的用途和功能需求。以下是一些常见的实现方法: 使用钩子(Hooks)和过滤器(Filters) 钩子和过滤器是一种常见的插件架…