首页 > 代码库 > 单向链表
单向链表
<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); ?>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。