栈的应用实例———一个超长的栈代码,加详解

<!--栈的应用实例-->

<?php
	$tracks=array();//定义一个全局栈,以存放状态
	
	//进入时,记录状态
	function enter_track($name)
	{
		global $tracks;//str_repeat() 函数把字符串重复指定的次数。
		echo str_repeat("&nbsp;",count($tracks));/*count()返回数组中元素的数目,
		功能为入栈前,统计栈的长度*/
		array_push($tracks,$name);//array_push() 函数向第一个参数的数组尾部添加一个或多个元素(入栈),然后返回新数组的长度。
		echo"进入 $name (当前栈:".join("->",$tracks).")<br>\n";
	}

	//退出时,释放状态
	function exit_track()
	{
		global $tracks;
		$ret=array_pop($tracks);//array_pop() 函数删除数组中的最后一个元素。
		echo str_repeat("&nbsp;",count($tracks));//出栈后,统计栈的长度
		echo "$ret 退出...<br>\n";
	}

	//测试函数
	function test_step_one()
	{
		enter_track("One");
		exit_track();
	}

	function test_step_two()
	{
		enter_track("Two");
		test_step_one();
		exit_track();
	}
	function test_step_three()
	{
		enter_track("Three");
		test_step_one();
		test_step_two();
		exit_track();
	}

	//执行测试

enter_track("OuterZero");
test_step_three();
exit_track();
?>

一个超级长的基本入栈和出栈的代码
结果如下:
进入 OuterZero (当前栈:OuterZero)
进入 Three (当前栈:OuterZero->Three)
进入 One (当前栈:OuterZero->Three->One)
One 退出…
进入 Two (当前栈:OuterZero->Three->Two)
进入 One (当前栈:OuterZero->Three->Two->One)
One 退出…
Two 退出…
Three 退出…
OuterZero 退出…
小细节&nbsp这个代表着空格,上面还有各个数组函数的运用基本能看明白,也码了一遍,但要自己写还是很困难的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值