栈
1. 栈(stack)
只允许一端进行删除和添加操作的线性表
2. 术语
栈顶、栈底、空栈
3. 实列
class stack {
private $stack = []; // 存放栈中元素
private $maxSize = 10; // 栈的最大个数
private $top = -1; // 栈顶指针,初始为-1,
// 是否为空
public function isEmpty() {
return $this->top === 1;
}
// 是否已满
public function isAll() {
return count($this->stack) === $this->maxSize;
}
// 入栈
public function push($data) {
if ($this->isAll()) {
return "栈已满";
}
$this->stack[++$this->top] = $data; // ++top,先让top加1再使用
return true;
// 如果top指针初始为0,
// 使用 $this->stack[$this->top++] = $data;
}
// 出栈
public function pull() {
if($this->isEmpty()) {
return '空栈';
}
$current = $this->top;
// $this->top--; // 数据残留,逻辑上删除
unset($this->stack[$this->top--]); // top--,先使用top再减1
return $this->stack[$current];
// 如果top指针初始为0
// 使用 --$this->top;
}
// 获取所有
public function get () {
return $this->stack;
}
}
$stack = new stack();
$stack->push('1');
$stack->push('2');
$stack->push('3');
$stack->pull();
print_r($stack->get());
3. 共享栈
两个栈共享一个存储空间,从两边依次往中间增长
0栈 初始指针为 top0 = -1,
1栈 初始指针为 top1 = $this->maxSize
栈满条件:top0+1 = top1;

浙公网安备 33010602011771号