php简单的堆栈操作

直接看代码:

class Stackeob implements IteratorAggregate
{
private $data;
private $count;
public function __construct($data=null)
{
$this->count = 0;
$this->data = array();
if(!is_null($data))
$this->copyData($data);
}
public function push($data)
{
++$this->count;
array_push($this->data,$data);
}
public function pop()
{
if(!$this->count)
return false;
$this->count--;
return array_pop($this->data);
}
public function peek()
{
if(!$this->count)
return false;
return $this->data[$this->count()-1];
}
public function contains($item)
{
return array_search($item,$this->data,true)!==false;
}
public function clean()
{
$this->count = 0;
$this->data = array();
}
public function count()
{
return $this->count;
}
public function copyData($data)
{
if(is_array($data))
{
$this->clean();
foreach ($data as $value)
{
$this->push($value);
}
}
elseif (!is_null($data))
exit('不是数组的其它格式');
}
public function toArray()
{
return $this->data;
}
public function getIterator()
{
return new StackIterator($this->data);
}
}

/*StackIterator实现了Iterator接口 提供一个统一的迭代方法*/
class StackIterator implements Iterator
{
/*
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
*/
private $data;
private $index;
public function __construct(&$data)
{
$this->data = $data;
$this->index= 0;
}
public function current()
{
return $this->data[$this->index];
}
public function key()
{
return $this->index;
}
public function next()
{
$this->index++;
}
public function rewind()
{
$this->index = 0;
}
public function valid()
{
return $this->current()!==false;
}
}

/*
$a = array('a','b','c','d','e');
$b = new Stackeob($a); //实例化栈
$b->push('test'); //压入数据
echo $b->pop(); //弹出数据,后进先出 弹出test
//遍历栈内容
foreach ($b as $key=>$val)
{
echo $key;
echo $val;
}
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值