双向链表可以解决的问题
可以完成自我删除,效率相对高,不需要辅助结点
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=gbk"/>
</head>
<h1>双向链表完成英雄排行管理</h1>
<br/>
<a href="#">查询英雄</a>
<a href="#">添加英雄</a>
<a href="#">删除英雄</a>
<a href="#">修改英雄</a>
<?php
//使用php的面向对象的方式来完成
class Hero{
public $pre=null;//表示指向前一个节点的引用
public $no;
public $name;
public $nickname;
public $next=null;//表示指向后一个节点的引用
public function __construct($no='',$name='',$nickname=''){
$this->no=$no;
$this->name=$name;
$this->nickname=$nickname;
}
//添加hero,这里我们会构建一个双向链表
public static function addHero($head,$hero){
//$head结点不能动
$cur=$head;//辅助引用$cur
//$isExist假设不存在
$isExist=false;
//看看目前这个链表是不是空
//如果不是空结点,按照排名来添加
//找到添加的位置
while($cur->next!=null){
if($cur->next->no > $hero->no){
//说明$hero就应该加入到$cur的后面
break;
}else if($cur->next->no==$hero->no){
$isExist=true;
echo '<br />不能添加重复的hero';
}
//继续判断
$cur=$cur->next;
}
//退出while时,我们只需要把$hero添加到$cur后面饥渴即可
if(!$isExist){
//比如添加的就是末尾
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 delHero($head,$herono){
//不用辅助结点
$cur=$head->next;
$isFind=false;
while($cur!=null){
if($cur->no==$herono){
$isFind=true;
break;
}
$cur=$cur->next;
}
if($isFind==true){
//删除
if($cur->next!=null){
$cur->next->pre=$cur->pre;
}
$cur->pre->next=$cur->next;
echo '<br/>删除的英雄编号'.$cur->no;
}else{
echo '<br/>要删除的英雄没有';
}
}
//显示所有的英雄函数
public static function showHero($head){
$cur=$head;
while($cur->next!=null){
echo '<br/>编号='.$cur->next->no.'名字= '.$cur->next->name.'外号 '.$cur->next->nickname;
$cur=$cur->next;
}
}
}
//创建一个头结点
$head=new Hero();
$hero=new Hero(1,'宋江','及时雨');
Hero::addHero($head,$hero);
$hero=new Hero(2,'卢俊义','玉麒麟');
Hero::addHero($head,$hero);
$hero=new Hero(6,'林冲','豹子头');
Hero::addHero($head,$hero);
$hero=new Hero(3,'吴用','智多星');
Hero::addHero($head,$hero);
$hero=new Hero(4,'公孙胜','入云龙');
Hero::addHero($head,$hero);
echo '<br />英雄排行榜';
Hero::showHero($head);
Hero::delHero($head,1);
echo '<br />删除后的英雄排行榜';
Hero::showHero($head);
?>
</html>