单链表实现水浒英雄榜
在这些人的叽叽喳喳中,搞定了单链表。
<?php
class hero{
public $no;
public $name;
public $nickName;
public $next=null;//默认为结尾
function __construct($no="",$name="",$nickName=""){
$this->no = $no;
$this->name = $name;
$this->nickName = $nickName;
}
}
class linkList{
public $head = "";
public $cur = "";
public function __construct(){
$this->head = new hero();
}
public function addHero($hero=""){
$this->cur = $this->head;
while($this->cur->next!=null){//找到单链表结尾
$this->cur = $this->cur->next;
}
$this->cur->next = $hero;
}
public function deleteHero($hero){
$this->cur = $this->head;
$flag = false;
while($this->cur->next!=null){
if($this->cur->next->no==$hero->no){
$this->cur->next = $this->cur->next->next;//删除的时候单链表不能断掉。
$flag = true;
break;
}else{
$this->cur = $this->cur->next;
}
}
if($flag){
echo "删除成功<br/>";
}else{
echo "没有该英雄<br/>";
}
}
public function updateHero($hero){
$this->cur = $this->head;
$flag = false;
while($this->cur->next!=null){
if($this->cur->next->no==$hero->no){
$hero->next = $this->cur->next->next; //更新的时候单链表不断
$this->cur->next = $hero;
$flag = true;
break;
}else{
$this->cur = $this->cur->next;
}
}
if($flag){
echo "替换成功<br/>";
}else{
echo "没有该英雄<br/>";
}
}
public function show(){
$this->cur = $this->head;
while($this->cur->next!=null){
echo "编号为".$this->cur->next->no."的hero的name是".$this->cur->next->name."绰号是".$this->cur->next->nickName."<br/>";
$this->cur = $this->cur->next;
}
}
}
header("Content-Type:text/html; charset=utf-8");
$head = new hero();
$linListInstance = new linkList();
$songJiang = new hero(1,"宋江","及时雨");
$linListInstance->addHero($songJiang);
$luJunyi = new hero(2,"卢俊义","艺人");
$linListInstance->addHero($luJunyi);
$linChong = new hero(3,"林冲","豹子头");
$linListInstance->addHero($linChong);
$linListInstance->show();
$linListInstance->deleteHero($luJunyi);
$linListInstance->deleteHero($songJiang);
$hero = new hero(4,"李广","玉面佛");
$linListInstance->updateHero($hero);
$linListInstance->show();
如果感觉不错,请
赞
一个!
by simpman
by simpman
浙公网安备 33010602011771号