Stack
A stack is a LIFO structure: the last value pushed is the first value popped.
先从这个心智模型开始
A stack is a LIFO structure: the last value pushed is the first value popped.
它如何工作,不堆砌不必要的术语
Think of a stack of plates. You add and remove from one end only.
Core operations are push, pop and peek/top. With a good implementation they are O(1).
把算法读成一连串决策
Push adds to the top.
Pop removes and returns the top.
Peek reads the top without removing it.
push(1), push(2), pop() returns 2.
class Stack {
#items = [];
push(value) { this.#items.push(value); }
pop() { return this.#items.pop(); }
peek() { return this.#items.at(-1); }
get size() { return this.#items.length; }
}不要死记语法。跟踪每一行中发生变化的状态,并把它与上面描述的不变量联系起来。
push/pop O(1)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
适用场景
- Undo/redo
- Expression parsing
- DFS and backtracking
通常哪里会出错
- Popping from an empty stack without handling it.
- Using Array.shift() and accidentally making operations O(n).
专业回答结构
Say LIFO first, then name push/pop/peek and one real use such as call stacks or parsing.
What problem does Stack solve?
A stack is a LIFO structure: the last value pushed is the first value popped.
关于复杂度应该提到什么?
Its typical cost here is push/pop O(1), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
最常见的错误是什么?
Popping from an empty stack without handling it.