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; }*/
页:
[1]