php 实现常用数据结构之链表
最近在恶补数据结构相关的知识,看到链表相关的一些算法,就用 PHP 简单实现了单链表的创建。
添加节点相关类:
<?php namespace App\Libraries; class ListNode { //节点数据域 public $data; //节点指针域 public $next; //构建节点 public function __construct($data = null, $next = null) { $this->data = $data; $this->next = $next; } }
单链表相关操作类:
<?php namespace App\Libraries; class SingleLinkList { //头部插入建立单链表 public function headInsert($n) { //新建头结点 $head = new ListNode(); for ($i=$n; $i > 0; $i--) { //添加节点 $newNode = new ListNode($i, $head->next); $head->next = $newNode; } return $head; } //尾部插入建立单链表 public function tailInsert($n) { //新建头尾节点,指向同一个节点 $head = $tail = new ListNode(); for ($i=1; $i <= $n; $i++) { //添加节点 $newNode = new ListNode($i); //将尾结点指针指向新的节点 $tail->next = $newNode; //将新节点标记为尾结点 $tail = $newNode; } return $head; } }
使用
立即学习“PHP免费学习笔记(深入)”;
<?php namespace App\Http\Controllers; // use Illuminate\Http\Request; use App\Libraries\SingleLinkList; class IndexController extends Controller { public function index () { $list = new SingleLinkList(); dd($list->headInsert(10)); //dd($list->tailInsert(10)); } }
以上就是PHP 实现常用数据结构之链表的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号