当前位置:首页 > PHP

php 实现单链表

2026-02-13 13:42:55PHP

单链表的基本概念

单链表是一种线性数据结构,由一系列节点组成,每个节点包含数据域和指向下一个节点的指针域。最后一个节点的指针域通常指向 NULL,表示链表结束。

php 实现单链表

单链表的节点结构

在 PHP 中,单链表的节点可以用类表示:

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->insertAtTail(20);
$list->insertAtTail(30);
$list->printList(); // 输出: 10 -> 20 -> 30 -> NULL

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

注意事项

  • PHP 是弱类型语言,节点的数据域可以存储任意类型的数据。
  • 在删除节点时,需处理头节点和中间节点的不同情况。
  • 遍历链表时需检查当前节点是否为 NULL,避免空指针异常。

通过上述方法,可以在 PHP 中实现基本的单链表操作。

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

相关文章

php验证码的实现

php验证码的实现

PHP 验证码实现方法 使用 GD 库生成基础验证码 创建画布并生成随机字符串作为验证码内容: session_start(); $width = 120; $height = 40; $image…

php队列的实现

php队列的实现

PHP队列的实现方式 PHP中实现队列功能可以通过多种方式,根据需求选择适合的方案: 使用数组实现基础队列 PHP数组本身支持队列操作,利用array_push和array_shift函数: $q…

php实现即时通讯

php实现即时通讯

PHP 实现即时通讯的方案 即时通讯(IM)可以通过多种方式实现,PHP 作为服务器端语言,通常需要结合前端技术(如 WebSocket、AJAX)或第三方服务来实现实时通信。以下是几种常见的实现方式…

php 线程实现

php 线程实现

PHP 线程实现方法 PHP 本身是单线程语言,但可以通过扩展或库实现多线程功能。以下是几种常见的实现方式: 使用 pthreads 扩展 pthreads 是一个 PHP 扩展,允许在 PHP 中…

php登陆功能实现

php登陆功能实现

实现PHP登录功能 数据库准备 创建一个用户表存储登录信息,基本字段包括用户名、密码(需加密)等: CREATE TABLE users ( id INT AUTO_INCREMENT PR…

php实现进度条

php实现进度条

PHP 实现进度条的方法 使用 HTML 和 CSS 结合 PHP 实现进度条 在 PHP 中,进度条通常通过 HTML 和 CSS 实现,PHP 负责计算进度并更新前端显示。 <di…