当前位置:首页 > 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;
    }
}

插入节点到链表头部

在链表头部插入新节点:

php链表实现

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;
}

删除指定值的节点

遍历链表找到匹配节点并调整指针:

php链表实现

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指针,确保逻辑一致。

应用示例

$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可以通过结合其他技术和工具来实现直播功能。以下是几种常见的方法: 使用流媒体服务器 配置流媒体服务器如Nginx-RTMP、Red5或Wowza。这些服务器支持RTMP协…

php实现注册

php实现注册

注册功能实现步骤 数据库准备 创建用户表,包含字段如id、username、password、email等。示例SQL: CREATE TABLE users ( id INT AUTO_I…

php队列的实现

php队列的实现

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

php实现推送

php实现推送

PHP 实现推送功能的方法 PHP 实现推送功能可以通过多种方式完成,包括 WebSocket、Server-Sent Events (SSE)、长轮询或第三方推送服务。以下是几种常见的方法: 使用…

php搜索功能的实现

php搜索功能的实现

实现PHP搜索功能的方法 数据库搜索 使用SQL的LIKE语句进行模糊匹配,适用于简单的搜索需求。 $searchTerm = $_GET['search']; $query = "SELECT *…

php实现发帖

php实现发帖

PHP 实现发帖功能 要在 PHP 中实现发帖功能,通常需要结合数据库操作(如 MySQL)和前端表单提交。以下是实现发帖功能的关键步骤: 数据库表设计 创建一个帖子表(posts)存储发帖内容,基…