码迷,mamicode.com
首页 > 其他好文 > 详细

单向链表

时间:2014-07-26 15:42:43      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:os   io   cti   ar   new   php   har   ad   

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



单向链表,布布扣,bubuko.com

单向链表

标签:os   io   cti   ar   new   php   har   ad   

原文地址:http://my.oschina.net/u/946060/blog/295042

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!