当前位置:首页 > PHP

php 实现单链表

2026-02-13 13:42:55PHP

单链表的基本概念

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

单链表的节点结构

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

class ListNode {
    public $data; // 数据域
    public $next; // 指针域

    public function __construct($data) {
        $this->data = $data;
        $this->next = null;
    }
}

单链表的实现

以下是单链表的常见操作实现,包括插入、删除和遍历。

php 实现单链表

初始化链表

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中,递归需要明确的终止条件(基线条件),否则会导致无限循环。 递归实现阶乘 阶乘是经典的递归案例,n! =…

php 实现登录

php 实现登录

PHP 登录功能实现 使用 PHP 实现登录功能通常需要结合数据库验证和会话管理。以下是一个基本的登录实现流程: 数据库准备 创建用户表存储用户名和密码(建议使用哈希加密): CREATE TAB…

php 实现购物车

php 实现购物车

PHP 实现购物车功能 购物车功能是电子商务网站的核心部分,可以通过 PHP 和 Session 或数据库来实现。以下是两种常见的实现方式: 使用 Session 存储购物车数据 Session 是…

php实现跳转

php实现跳转

PHP 实现页面跳转的方法 在 PHP 中实现页面跳转有多种方式,以下是常见的几种方法及其适用场景: 使用 header() 函数 通过 header() 函数发送 HTTP 头部信息实现跳转。注意…

php实现即时通讯

php实现即时通讯

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

php实现mvc

php实现mvc

PHP 实现 MVC 架构 MVC(Model-View-Controller)是一种常用的软件设计模式,将应用程序分为三个核心组件:模型(Model)、视图(View)和控制器(Controller…