php实现堆栈

席嘉祯
2023-12-01

<?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;
}

 

转载于:https://www.cnblogs.com/lijintao1025/p/8532957.html

 类似资料: