<?php
/**双向链表 -- 水浒传英雄排行版*/
class hero{
public $name = '';
public $no ='';
public $cname = '';
public $next = '';
public $pre = '';
public function __construct($no = '',$name='',$cname=''){
$this->no = $no;
$this->name = $name;
$this->cname = $cname;
}
//显示英雄链表
public static function showHero($head){
$cur = $head;
while($cur->next != null){
echo '英雄编号:'.$cur->next->no.' ';
echo '英雄姓名:'.$cur->next->name.' ';
echo '英雄昵称:'.$cur->next->cname.' ';
echo '<br />';
$cur = $cur->next;
}
echo '<hr />';
}
//英雄按排序加入
public static function addHero($head,$hero){
$cur = $head;
$isExits = false;
while($cur->next != null){
if($cur->next->no > $hero->no){
break;
}elseif($cur->next->no == $hero->no){
$isExits = true;
}
$cur = $cur->next;
}
if(!$isExits){
if($cur->next != null){
$hero->next = $cur->next;
}
$hero->pre = $cur;
if($cur->next != null){
$cur->next->pre = $hero;
}
$cur->next = $hero;
}
}
//修改英雄
public static function editHero($head,$hero){
$cur = $head;
while($cur->next != null){
if($cur->next == $hero){
break;
}
$cur = $cur->next;
}
$cur->next->name = $hero->name;
$cur->next->cname = $hero->cname;
}
//删除英雄
public static function delHero($head,$hero){
$cur = $head;
if($cur == null){
return false;
}
while($cur->next != null){
if($cur == $hero){
break;
}
$cur = $cur->next;
}
if($cur->next != null){
$cur->next->pre = $cur->pre;
}
$cur->pre->next = $cur->next;
}
}
$head = new hero();
$songjiang = new hero(1,'宋江','及时雨');
$lujunyi = new hero(2,'卢俊义','玉麒麟');
$linchong = new hero(6,'林冲','豹子头');
$wuyong = new hero(3,'吴用','智多星');
hero::addHero($head,$songjiang);
hero::addHero($head,$lujunyi);
hero::addHero($head,$linchong);
hero::addHero($head,$wuyong);
hero::showHero($head);
$wuyong->name = '吴用2';
hero::editHero($head,$wuyong);
hero::showHero($head);
hero::delHero($head,$wuyong);
hero::showHero($head);
?>
</body>
</html>
双向链表的知识讲解:http://blog.csdn.net/wenximalong/article/details/8308881
浙公网安备 33010602011771号