PHP小教程之實現(xiàn)鏈表
看了很久數(shù)據(jù)結(jié)構(gòu)但是沒有怎么用過,在網(wǎng)上看到了關(guān)于PHP的數(shù)據(jù)結(jié)構(gòu),學(xué)習(xí)了一下,與大家一起分享一下。
class Hero
{
public $no;//排名
public $name;//名字
public $next=null;//$next是一個引用,指向另外一個Hero的對象實例
public function __construct($no='',$name='')
{
$this->no=$no;
$this->name=$name;
}
static public function showList($head)
{
$cur = $head;
while($cur->next!=null)
{
echo "排名:".$cur->next->no.",名字:".$cur->next->name."<br>";
$cur = $cur->next;
}
}
//普通插入
static public function addHero($head,$hero)
{
$cur = $head;
while($cur->next!=null)
{
$cur = $cur->next;
}
$cur->next=$hero;
}
//有序的鏈表的插入
static public function addHeroSorted($head,$hero)
{
$cur = $head;
$addNo = $hero->no;
while($cur->next->no <= $addNo)
{
$cur = $cur->next;
}
/*$tep = new Hero();
$tep = $cur->next;
$cur->next = $hero;
$hero->next =$tep;*/
$hero->next=$cur->next;
$cur->next=$hero;
}
static public function deleteHero($head,$no)
{
$cur = $head;
while($cur->next->no != $no && $cur->next!= null)
{
$cur = $cur->next;
}
if($cur->next->no != null)
{
$cur->next = $cur->next->next;
echo "刪除成功<br>";
}
else
{
echo "沒有找到<br>";
}
}
static public function updateHero($head,$hero)
{
$cur = $head;
while($cur->next->no != $hero->no && $cur->next!= null)
{
$cur = $cur->next;
}
if($cur->next->no != null)
{
$hero->next = $cur->next->next;
$cur->next = $hero;
echo "更改成功<br>";
}
else
{
echo "沒有找到<br>";
}
}
}
//創(chuàng)建head頭
$head = new Hero();
//第一個
$hero = new Hero(1,'111');
//連接
$head->next = $hero;
//第二個
$hero2 = new Hero(3,'333');
//連接
Hero::addHero($head,$hero2);
$hero3 = new Hero(2,'222');
Hero::addHeroSorted($head,$hero3);
//顯示
Hero::showlist($head);
//刪除
Hero::deleteHero($head,4);
//顯示
Hero::showlist($head);
//更改
$hero4=new Hero(2,'xxx');
Hero::updateHero($head,$hero4);
//顯示
Hero::showlist($head);
有序的插入的話需要遍歷一遍鏈表,鏈表的一些知識就不介紹了哈。這里主要分享一下代碼。
相關(guān)文章
PHP設(shè)計模式之建造者模式(Builder)原理與用法案例詳解
這篇文章主要介紹了PHP設(shè)計模式之建造者模式(Builder)原理與用法,結(jié)合具體實例形式詳細(xì)Fenix了建造者模式的概念、原理、用法及操作注意事項,需要的朋友可以參考下2019-12-12
windows系統(tǒng)php環(huán)境安裝swoole具體步驟
這篇文章主要介紹了windows系統(tǒng)php環(huán)境安裝swoole具體步驟,swoole目前是比較熱門的一個擴(kuò)展插件,有需要的同學(xué)可以學(xué)習(xí)下2021-03-03
PHP實現(xiàn)把文本中的URL轉(zhuǎn)換為鏈接的auolink()函數(shù)分享
這篇文章主要介紹了PHP實現(xiàn)把文本中的URL轉(zhuǎn)換為鏈接的auolink()函數(shù)分享,非常簡潔易用的一個函數(shù),原作者還有另外一些很Nice的PHP函數(shù),需要的朋友可以參考下2014-07-07
PhpStorm 2020.3:新增開箱即用的PHP 8屬性(推薦)
這篇文章主要介紹了PhpStorm 2020.3:新增開箱即用的PHP 8屬性的相關(guān)資料,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
Thinkphp 框架配置操作之動態(tài)配置、擴(kuò)展配置及批量配置實例分析
這篇文章主要介紹了Thinkphp 框架配置操作之動態(tài)配置、擴(kuò)展配置及批量配置,結(jié)合實例形式分析了Thinkphp配置操作中動態(tài)配置、擴(kuò)展配置及批量配置基本原理、實現(xiàn)方法與相關(guān)注意事項,需要的朋友可以參考下2020-05-05

