定义
只允许在一端进行插入和删除操作的线性结构,称为栈。
- 栈顶
- 栈底
性质
先进后出,First In Last Out,FILO
基本操作
head:表示栈上最上面一个有元素的位置的上一个位置
const int maxn = 1e5+5;//栈的最大容量
int sta[maxn]; //栈的存储空间
int head = 0; //栈顶
- 添加元素
void push(int n){
sta[head++] = n; //插入,为什么是top++,不是++top?
}
- 删除元素
void pop(){
return top--;
}
- 得到最上面的元素的值
int top() {
return sta[top-1];
}
- 栈是否空
bool empty() {
return top == 0;
}
模板
template<typename T = int,int siz = maxn>
struct mystack{
T sta[siz+5];
int head = 0;
void clear() { head = 0;}
void push(T a) { sta[head++] = a;}
void pop(){head--;}
T top() { return sta[head-1];}
bool empty() { return head == 0;}
int size() { return head;}
};
总结
栈能解决的问题
- 线性的一对元素匹配类(是否括号匹配)
- 后缀表达式:栈还可以用于计算后缀表达式(也称为逆波兰表达式)的值。
- 具有LIFO特性的操作
- 其它匹配类问题
练习题目
- [
leetcodecn remove-all-adjacent-duplicates-in-string: 删除字符串中的所有相邻重复项] - [
leetcodecn valid-parentheses: 有效的括号] - [
luogu P1739: 表达式括号匹配] - [
luogu P1241: 括号序列] - [
luogu P1449: 后缀表达式] - [
luogu P4387: 【深基15.习9】验证栈序列] - [
noi_openjudge ch0303-1696: 波兰表达式] - [
noi_openjudge ch0303-6263: 布尔表达式] - [
leetcodecn valid-palindrome: 图书整理 II] - luogu P9753 [CSP-S 2023] 消消乐 50分算法
考把中缀转后缀的题目
- leetcode 224. 基本计算器
- leetcode 227. 基本计算器 II
- leetcode 772. 基本计算器 III