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."<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);

きちんと挿入するにはチェーンを通していく必要があります。チェーンの知識は紹介しません。ここでは主にコードを共有します。