Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php 链表如何实现

作者:凌傲天   发布日期:2024-06-23   浏览:638

在PHP中,可以使用类来实现链表。下面是一个简单的示例:

class Node {
    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 insert($data) {
        $newNode = new Node($data);

        if ($this->head === null) {
            $this->head = $newNode;
        } else {
            $current = $this->head;
            while ($current->next !== null) {
                $current = $current->next;
            }
            $current->next = $newNode;
        }
    }

    public function display() {
        $current = $this->head;
        while ($current !== null) {
            echo $current->data . " ";
            $current = $current->next;
        }
    }
}

// 示例用法
$linkedList = new LinkedList();
$linkedList->insert(1);
$linkedList->insert(2);
$linkedList->insert(3);
$linkedList->display(); // 输出: 1 2 3

在上面的示例中,Node类表示链表的节点,包含一个数据项和一个指向下一个节点的指针。LinkedList类表示链表,具有插入和显示链表的方法。在插入方法中,如果链表为空,新节点将成为头节点,否则,将遍历链表直到找到最后一个节点,然后将新节点插入到最后一个节点的后面。在显示方法中,将遍历链表并输出每个节点的数据项。

这只是链表的基本实现示例,你可以根据需要进行扩展和修改。

上一篇:php数组去掉空值的方法

下一篇:ubuntu 怎么安装 php curl

大家都在看

php session用法

php 定义常量

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站