单项链表

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>英雄排行榜</h1>
<?php

class Hero{
public $id; //编号
public $name; //姓名
public $next = null; //

public function __construct($id = '',$name = '')
{
$this->id = $id;
$this->name = $name;
}

}

//按照id从小到大顺序添加英雄
function addHero($head,$hero)
{
//链表头部不能动
$cur = $head;
while ($cur->next != null){
if($cur->next->id > $hero->id){
//新增到next前面
break;
}
$cur = $cur->next;
}
//跳出循环后,找到了添加英雄的位置
$hero->next = $cur->next;
$cur->next = $hero;
}

//展示英雄列表
function showHeros($head)
{
//链表头部不能动
$cur = $head;
while ($cur->next != null){
echo '<br/>id:' . $cur->next->id .',姓名:' . $cur->next->name;
// TODO 链表继续往下走,这行代码很重要
$cur = $cur->next;
}
}

//删除
function delHero($head,$id)
{
//链表头部不能动
$cur = $head;
$flag = false;
while ($cur->next != null){
if($cur->next->id == $id){
$flag = true;
break;
}
$cur = $cur->next;
}
if($flag){
$cur->next = $cur->next->next;
}else{
echo '没有此编号的英雄id:' . $id;
}
}


$head = new Hero();
$hero = new Hero('1','jack');
addHero($head,$hero);

$hero = new Hero('6','lucy');
addHero($head,$hero);

$hero = new Hero('3','tom');
addHero($head,$hero);

$hero = new Hero('4','jim');
addHero($head,$hero);

showHeros($head);
delHero($head,4);
showHeros($head);
?>
</body>
</html>




posted @ 2020-08-28 11:57  Kris-Q  阅读(126)  评论(0编辑  收藏  举报