PHP 实现常用数据结构之链表-php教程

资源魔 17 0
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
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开发自学

抱歉,评论功能暂时关闭!