單向鏈表

<meta charset='utf-8' />
<?php
    class Hero
    {
        public $no;
        public $name;
        public $nickname;
        public $next = null;

        public function __construct($no='',$name='',$nickname=''){
            $this->no = $no;
            $this->name = $name;
            $this->nickname = $nickname;
        }
    }

// 添加英雄
function addHero($head,$hero){
    $cur = $head;
    $flag = false;
    while($cur->next!=null){
        if ($cur->next->no > $hero->no) 
        {
            break;
        }else if ($cur->next->no == $hero->no){
            $flag = true;
            echo '英雄編號'.$hero->no.'的位置已經存在,請不要重複添加<br />';
        }
        $cur = $cur->next;
    }

    // 找到
    if ($flag==false) 
    {
        $hero->next = $cur->next;
        $cur->next = $hero;
    }
}

// 刪除英雄
function delHero($head,$herono){
    $cur = $head;
    while($cur->next!=null){
        if ($cur->next->no == $herono) 
        {
            // 找到
            break;
        }
        $cur = $cur->next;
    }

    // 找到就刪除
    if ($cur->next!=null) 
    {
        $cur->next = $cur->next->next;
    }else{
        echo '沒法找到編號爲'.$herono.'的英雄<br />';
    }
}

// 更新英雄
function updateHero($head,$hero){
    $cur = $head;
    while($cur->next!=null){
        if ($cur->next->no == $hero->no) 
        {
            // 找到
            break;
        }
        $cur = $cur->next;
    }

    // 更新
    if ($cur->next!=null) 
    {
        $cur->next->name = $hero->name;
        $cur->next->nickname = $hero->nickname;
    }else{
        echo '你要修改的英雄不存在<br />';
    }
}

// 遍歷英雄
function showHeros($head){
    $cur = $head;
    while($cur->next!=null){
        echo '當前英雄編號爲'.$cur->next->no.' 名字='.$cur->next->name.' 暱稱爲'.$cur->next->nickname.'<br />';
        $cur = $cur->next;
    }
}

$head = new Hero;

$hero = new Hero(1,'宋江','及時雨');
addHero($head,$hero);
$hero = new Hero(2,'盧俊義','玉麒麟');
addHero($head,$hero);
$hero = new Hero(6,'林沖','豹子頭');
addHero($head,$hero);
$hero = new Hero(3,'吳用','智多星');
addHero($head,$hero);
$hero = new Hero(2,'盧俊義','玉麒麟');
addHero($head,$hero);

showHeros($head);

delHero($head,3);
showHeros($head);

$hero = new Hero(2,'我','老大');
updateHero($head,$hero);
showHeros($head);
?>
相關文章
相關標籤/搜索