//单链表
class hero{
var $name;
var $sn;
var $names;
var $next;
public function __construct($sn='',$name='',$names='',$next=''){
$this->name=$name;
$this->sn=$sn;
$this->names=$names;
$this->next=$next;
}
}
//头结点
$head=new hero();
//增加链表节点
function addHero($head,$hero){
$cul=$head;
while($cul->next!=null){
if($cul->next->sn>$hero->sn){
$hero->next=$cul->next;
$cul->next=$hero;
$flag='';
break;
}
$cul=$cul->next;
}
if(!isset($flag))
$cul->next=$hero;
}
//遍历链表
function showHero($head){
$cul=$head;
while($cul->next!=null){
echo $cul->next->sn.' '.$cul->next->name.' '.$cul->next->names.'
';
$cul=$cul->next;
}
//echo 'a'.$head->name.'
';
}
//删除链表节点
function delHero($head,$sn){
$cul=$head;
while($cul->next!=null){
if($cul->next->sn==$sn){
$cul->next=$cul->next->next;
$flag='';
break;
}
$cul=$cul->next;
}
if(!isset($flag))echo $sn.'的英雄没找到
';
}
//修改节点
function editHero($head,$hero){
$cul=$head;
while($cul->next!=null){
if($hero->sn==$cul->next->sn){
$hero->next=$cul->next->next;
$cul->next=$hero;
$flag='';
break;
}
$cul=$cul->next;
}
if(!isset($flag))echo $hero->sn.'的英雄没找到
';
}
//测试
//增加节点
$hero=new hero(1,'小宝','小宝宝');
addHero($head,$hero);
$hero=new hero(2,'小贝','小贝贝');
addHero($head,$hero);
$hero=new hero(3,'小白','小白白');
addHero($head,$hero);
$hero=new hero('6','香兰','向兰兰');
addHero($head,$hero);
$hero=new hero('4','李峰','李峰分');
addHero($head,$hero);
$hero=new hero('5','刘雪','刘雪雪');
addHero($head,$hero);
$hero=new hero('7','寒梅','韩梅梅');
addHero($head,$hero);
//遍历节点
showHero($head);
//删除节点
echo '
删除后
';
delHero($head,2);
showHero($head);
//修改节点
echo '
修改后
';
$hero=new hero('4','赵峰','赵凤凤');
editHero($head,$hero);
showHero($head);
?>