清华大学韩顺平讲师讲算法之三(下),环链表创建与删除

<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8'>
<title>/高性能的计算器/</title>
</head>
<body>
<?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;
	}
	public static function addHero($head,$hero){
		$cur=$head;//一个辅助点,不能动头
		$isExist=false;
		if($cur->next==null){
			$cur->next=$hero;
			$hero->pre=$cur;
		}else{
			///如果不是空节点,则按排名来添加
			
			while($cur->next!=null){
				if($cur->next->no>$hero->no){
					//说明$hero要加入在$cur的后面

				}else if($cur->next->no==$hero->no){
					$isExist=true;
					echo '<br>不能有相同编号';
				}
				$cur=$cur->next;
			}//while
			// 退出while时,我们只要把$hero添加到$cure后面即可
			if(!$isExist){
				//比如加的就是末
				if($cur->next !=null){//处理空表
					$hero->next=$cur->next;
				}
				$hero->pre=$cur;
				if($cur->next !=null){//处理空表
					$cur->next->pre=$hero;
				}
				$cur->next=$hero;
			}
		}//if



	}//addHero

		public static function showHero($head){
			$cur=$head;
			while($cur->next !=null){
				echo '<br>编号:'.$cur->no.'名字:'.$cur->name;
			$cur=$cur->next;
			}
			//当退出while
			echo '<br>编号是:'.$cur->no.'名字:'.$cur->name;
		}//showHero
		public static function delHero($head,$herono){
			//不用辅助结点
			$cur=$head->next;
			if($cur==null){
				echo '一个空表,删除了没意义';
			}
			$isFind=false;
			while ($cur !=null) {
				if($cur->no == $herono){
					//找到了
					$isFind=true;
					break;

				}//if
				$cur=$cur->next;//向下找
			}//while
			if($isFind){
				//找到了可以删除
				//自我删除,不使用辅助结点
				if($cur->next !=null){
					$cur->next->pre=$cur->pre;
				}
				$cur->pre->next=$cur->next;

			}else{
				echo "找不到了,你输入的不对,没法子删除啊.";
			}//if
		}//delHero
}//class
	$head=new Hero();
	$hero=new Hero(1,'宋江','及时狗');
	Hero::addHero($head,$hero);

	$hero=new Hero(2,'吴用','一个老师');
	Hero::addHero($head,$hero);	

	$hero=new Hero(3,'林冲','教头');
	Hero::addHero($head,$hero);	
	Hero::showHero($head);

	//试试删除
	Hero::delHero($head,2);
	//
	echo '<br>'."删除的后的".'<br>';
	Hero::showHero($head);

	echo '<br><br>'.'其好处是自好删除,以后学习二叉树及其他,打下良好的基础';
?>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值