清华大学韩顺平讲师讲算法之一,单链表创建、显示、删除、修改

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP操作mysql多功能类</title>
<body>
<?php
	class Hero{
		public $no;
		public $name;
		public $nickname;

		public $next=null;//是一个引用,指向另一个结点的

		public function __construct($no='',$name='',$nickname=''){//不要写错了
			$this->no=$no;
			$this->name=$name;
			$this->nickname=$nickname;
		}

	function delHero($head,$herono){
		$cur=$head;
		while ($cur->next !=null) {
			if($cur->next->no ==$herono){
				//找到了退出吧
				break;
			}//if
			$cur=$cur->next;
		}//while
		
		if($cur->next !=null){
			//删除了
			$cur->next=$cur->next->next;
		}
	}
}//Hero
	//修改英雄
	function updateHero($head,$hero){
		//跑龙套的$cur
		$cur=$head;
		while($cur->next !=null){
			if($cur->next->no==$hero->no){
				break;
			}//if
			$cur=$cur->next;
		}
		//当退出while时,$cur->next==null为空,再到了队尾了
		if($cur->next==null){
			echo "no";
		}else{
			$cur->next->name=$hero->name;
		}
	}//updateHero
	function addHero($head,$hero){
		//1.直接加在链表最后加
		//2.安英雄的排行
		$cur=$head;
		/*while ( $cu->next !=null) {
			$cur=$cur->next;
		}//while
		$cur->next=$hero;*/
		while($cur->next !=null){
			if($cur->next->no >=$hero->no){
			break;
		}
			$cur=$cur->next;

		}
		$hero->next=$cur->next;
		$cur->next=$hero;
	}//addHero
	function showHeros($head){
		//遍历[必须知道什么时候到了最后]
		//为了不去改变$head的指向,我们可以使用一个临时变量$cur
		$cur=$head;
		while($cur->next !=NULL){
			echo '英雄的编号:'.$cur->next->no.'名字:'.$cur->next->name;
			//让cur移动,否则是死了
			$cur=$cur->next;
		}//while
	}//showHeros
	$head=new Hero();
	$hero=new Hero(1,'宋江','及时狗');
		//addHero($head,$hero);

	$head->next=$hero;

	$hero2=new Hero(2,"卢俊义",'一兄称');
	//addHero($head,$hero);
	$hero->next=$hero2;

	//单链表的遍历,是从head开始遍历的
	//$head头的值不能亦空,
 showHeros($head);
?>

</body>
</html>

对老师表示真诚的感谢与敬意,国内高校需要你这样的老师,感谢你的付出。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值