萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> PHP小教程之實現雙向鏈表

PHP小教程之實現雙向鏈表

 看了很久數據結構但是沒有怎麼用過,在網上看到了關於PHP的數據結構,學習了一下,與大家一起分享一下。

 

.代碼如下:
<?php
        class Hero
        {
            public $pre=null;
            public $no;
            public $name;
            public $next=null;
            public function __construct($no='',$name='')
            {
                $this->no=$no;
                $this->name=$name;
            }
            static public function addHero($head,$hero)
            {
                $cur = $head;
                $isExist=false;
                //判斷目前這個鏈表是否為空
                if($cur->next==null)
                {
                    $cur->next=$hero;
                    $hero->pre=$cur;
                }
                else
                {
                    //如果不是空節點,則安排名來添加
                    //找到添加的位置
                    while($cur->next!=null)
                    {
                        if($cur->next->no > $hero->no)
                        {
                            break;
                        }
                        else if($cur->next->no == $hero->no)
                        {
                            $isExist=true;
                            echo "<br>不能添加相同的編號";
                        }
                        $cur=$cur->next;
                    }
                    if(!$isExist)
                    {
                        if($cur->next!=null)
                        {
                            $hero->next=$cur->next;
                        }
                        $hero->pre=$cur;
                        if($cur->next!=null)
                        {
                            $hero->next->pre=$hero;
                        }
                        $cur->next=$hero;                    
                    }
                }
            }
            //遍歷
            static public function showHero($head)
            {
                $cur=$head;
                while($cur->next!=null)
            &n
copyright © 萬盛學電腦網 all rights reserved