php实现堆栈

<?php


/**
* 节点信息
*/

class node{

public $value ;// 节点的数据
function __construct($value){
$this->value = $value;
}
}

/**
*堆栈的实现
*/

class stack{
public $last;//指向尾部元素
public $stacklist;// 堆栈元素列表
public $size = 0;//队列节点个数

//出栈
function pop(){
if(0 == $this->size){
return ;
exit('the stack is empty!');
}

$data = $this->last;
array_pop($this->stacklist);
$this->last = end($this->stacklist);
$this->size--;
return $data;

}

// 入栈
function push($value){
$node = new node($value);
$this->last = $node;
$this->stacklist[] = $node;
$this->size++;
}
//返回栈顶元素,但是不出栈
function end(){

if($this->size > 0){
return end($this->stacklist)->value;
}
return false;


}


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


}


$stack = new stack();

for($i=0; $i<10; $i++){
$stack->push($i);
}


while($node = $stack->pop()){
echo $node->value,PHP_EOL;
}

 

posted @ 2018-03-09 11:35  jintaonote  阅读(296)  评论(0编辑  收藏  举报