首页 > 代码库 > 单向链表

单向链表

<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);
?>