Stack
栈
线性结构入门时间 push / pop O(1)空间 O(n)
后进先出(LIFO)。只在同一端压入和弹出,像一摞盘子。
动画
3
栈(LIFO):push 3
1 / 5
- 当前
讲解
函数调用、括号匹配、表达式求值、DFS 显式化、单调栈。
- 01push 把元素放到栈顶。
- 02pop 取走栈顶。
- 03peek / top 只看不取。
- 04可用数组或链表实现,数组更常见。
易错点
- 空栈 pop 会出错,先判 empty。
- 递归过深等价于栈溢出,可改为显式栈。
代码
const st = [];
st.push(class="text-accent">3); st.push(class="text-accent">8); st.push(class="text-accent">1);
const top = st.pop(); // class="text-accent">1
st.push(class="text-accent">5);