网络编程 
首页 > 网络编程 > 浏览文章

PHP小教程之实现链表

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

看了很久数据结构但是没有怎么用过,在网上看到了关于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."<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>";
        }
    }
}

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

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

上一篇:CI框架中集成CKEditor编辑器的教程
下一篇:浅谈Eclipse PDT调试PHP程序
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网