Home > Backend Development > PHP Tutorial > PHP implements linked lists of commonly used data structures

PHP implements linked lists of commonly used data structures

藏色散人
Release: 2023-04-07 13:02:01
forward
3088 people have browsed it

PHP implements the linked list of commonly used data structures

Recently, I have been supplementing the knowledge related to data structures and saw some algorithms related to linked lists, so I used PHP to simply implement the creation of a singly linked list. .

Add node related classes:

<?php
namespace App\Libraries;
class ListNode
{
    //节点数据域
    public $data;
    //节点指针域
    public $next;
    //构建节点
    public function __construct($data = null, $next = null)
    {
        $this->data = $data;
        $this->next = $next;
    }
}
Copy after login

Singly linked list related operation classes:

<?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;
    }
}
Copy after login

Use

<?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));
    }
}
Copy after login

The above is the detailed content of PHP implements linked lists of commonly used data structures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template