php栈

php的array 很强大,自带很多数组函数,可以直接当作数组,队列,栈,集合,字典来用


<?php 

#php5 没有内部类??
class Node{
	public $item;
	public $next;
} 


class Stack{
	private $first;
	private $n;

	
	function __construct(){
		$this->first=null;
		$this->n=0;
	}

	function isEmpty(){
		return $this->first==null;
	}

	function size(){
		return $this->n;
	}

	function push($item){
		$oldfirst=$this->first;
		$this->first=new Node();
		$this->first->item=$item;
		$this->first->next=$oldfirst;
		$this->n++;
	}

	function pop(){
		if($this->isEmpty())
			throw new Exception('no such element');
		$item=$this->first->item;
		$this->first=$this->first->next;
		$this->n--;
		return $item;
	}

	function peek(){
		if($this->isEmpty())
			throw new Exception('no such element');
		return $first->item;
	}

}


#首先,php的array函数 自带栈的功能
$a[]=1;
$a[]=2;
$a[]=3;
$a[]=4;
$a[]=5;

array_push($a, 6);
print_r($a);
print_r(array_pop($a));
print_r($a);

#Stack类 测试如下
try{

	$stack=new Stack();
	print_r($stack);

	$stack->push(1);
	$stack->push(2);
	$stack->push(3);
	$stack->push(4);
	$stack->push(5);

	print_r($stack->peek());
	print_r($stack);

	print_r($stack->pop());
	print_r($stack);

}catch(Exception $e){
	echo $e->getMessage();
}













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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值