栈
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;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律