题目
用数组实现栈,提供 push、pop、peek 与 isEmpty,遵循后进先出。输入契约为空栈,输出契约为具备标准栈操作的实例。样例 push(1)、push(2)、pop() 返回 2;空栈 pop 返回 undefined;push(1) 后 peek 返回 1。
解题思路
用内部数组保存元素。push 追加到数组末尾,pop 从末尾移除并返回,peek 读取末尾元素但不移除,isEmpty 判断长度是否为 0。所有操作都集中在数组末端,天然满足 LIFO。
参考实现要点
push 与 pop 在数组末尾操作,时间复杂度 O(1)。peek 用 length - 1 取下标。空栈 pop 返回 undefined,调用方需自行判空。实现不引入额外指针或容量管理,保持最小化。
常见错误
原文指出:用 shift/unshift 在数组头部操作会把复杂度变成 O(n),应始终使用末端。另一个相关问题是空栈调用 peek 返回 undefined,若调用方直接使用该值而不判空,容易产生隐性错误。
验证方式
用 Node.js 运行,按样例执行入栈与出栈,断言返回值与 isEmpty 状态;再测空栈的 pop 与 peek,确认返回 undefined。
代码示例
class Stack {
constructor() { this.items = []; }
push(item) { this.items.push(item); }
pop() { return this.items.pop(); }
peek() { return this.items[this.items.length - 1]; }
isEmpty() { return this.items.length === 0; }
}