最近在恶补数据结构相关的知识,看到链表相关的一些算法,就用 php 简单实现了单链表的创建。
添加节点相关类:
<?phpnamespace app\libraries;class listnode{ //节点数据域 public $data; //节点指针域 public $next; //构建节点 public function __construct($data = null, $next = null) { $this->data = $data; $this->next = $next; }}
单链表相关操作类:
<?phpnamespace 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; }}
使用
<?phpnamespace 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 实现常用数据结构之链表的详细内容。
