PHP   发布时间:2019-11-14  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了PHP小教程之实现链表大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

看了很久数据结构但是没有怎么用过,在网上看到了关于PHP的数据结构,学习了一下,与大家一起分享一下。

代码如下:
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."
";
$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 "删除成功
";
}
else
{
echo "没有找到
";
}
} 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 "更改成功
";
}
else
{
echo "没有找到
";
}
}
}

//创建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);

有序的插入的话需要遍历一遍链表,链表的一些知识就不介绍了哈。这里主要分享一下代码。

大佬总结

以上是大佬教程为你收集整理的PHP小教程之实现链表全部内容,希望文章能够帮你解决PHP小教程之实现链表所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: