当前位置:首页 > PHP

php链表实现

2026-03-12 19:43:39PHP

链表的基本概念

链表是一种线性数据结构,由节点(Node)组成,每个节点包含数据(data)和指向下一个节点的指针(next)。与数组不同,链表在内存中是非连续存储的,动态增删节点更高效。

单链表的PHP实现

定义节点类

链表的基础是节点,需定义一个Node类存储数据和指针:

class Node {
    public $data;
    public $next;

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

定义链表类

创建LinkedList类管理节点的增删查操作:

class LinkedList {
    private $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 "NULL\n";
}

双向链表的扩展实现

双向链表的节点包含前驱(prev)和后继(next)指针:

class DoublyNode {
    public $data;
    public $prev;
    public $next;

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

双向链表的插入与删除

需同时维护prevnext指针,确保逻辑一致。

php链表实现

应用示例

$list = new LinkedList();
$list->insertAtHead(3);
$list->insertAtTail(5);
$list->insertAtHead(1);
$list->printList(); // 输出: 1 -> 3 -> 5 -> NULL
$list->deleteNode(3);
$list->printList(); // 输出: 1 -> 5 -> NULL

通过上述实现,可完成链表的创建、插入、删除和遍历操作。实际应用中可根据需求扩展更多功能,如反转链表、检测环等。

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

相关文章

php实现搜索功能

php实现搜索功能

实现基本的搜索功能 在PHP中实现搜索功能通常涉及数据库查询。以下是一个简单的实现方式,假设使用MySQL数据库: <?php // 连接数据库 $conn = new mysqli('loc…

php实现排序

php实现排序

PHP 数组排序方法 PHP 提供了多种内置函数用于数组排序,适用于不同的排序需求。以下是常见的排序方法: 按值升序排序 sort() 函数对数组按值升序排序,重置键名(索引数组适用): $num…

基于php的设计与实现

基于php的设计与实现

PHP 设计与实现的关键要素 环境搭建与框架选择 PHP开发需配置服务器环境(如Apache/Nginx)、PHP版本(建议7.4+)及数据库(MySQL/MariaDB)。主流框架包括Laravel…

php实现静态

php实现静态

静态化实现方法 PHP实现静态化主要通过生成HTML文件或缓存机制来减少服务器动态解析的开销。以下是几种常见方法: 生成静态HTML文件 通过file_put_contents()将动态内容保存为H…

php实现博客

php实现博客

使用PHP实现博客系统 数据库设计 创建数据库表存储博客文章和用户信息。常见的表包括posts(文章)和users(用户)。 CREATE TABLE users ( id INT AUTO…

php实现下载

php实现下载

PHP实现文件下载 使用PHP实现文件下载可以通过设置HTTP头部信息强制浏览器下载文件而非直接打开。以下是几种常见的方法: 方法一:直接输出文件内容 $file_path = 'path/to/…