1 定义
只允许在一端进行插入和删除操作的线性结构,称为栈。
- 栈顶
- 栈底
2 性质
先进后出,First In Last Out,FILO
3 基本操作
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;
}
4 模板
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;}
};
# 直接使用 list 模拟栈
stack = []
stack.append(1) # 入栈 push
top = stack[-1] # 查看栈顶 peek → 3
item = stack.pop() # 出栈 pop → 3
is_empty = not stack # 判空
size = len(stack) # 大小
## 方法2 : 继承 list,改名
class Stack(list):
push = list.append
empty = lambda self: not self
size = lambda self: len(self)
# 使用 class 封装,便于扩展和加保护
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self._items[-1]
def is_empty(self) -> bool:
return not self._items
def __len__(self) -> int:
return len(self._items)
def __repr__(self):
return f"Stack({self._items})"
s = Stack()
s.push(1); s.push(2)
print(s.peek()) # 2
print(s.pop()) # 2
print(len(s)) # 1
5 总结
说明栈能解决的问题
- 线性的一对元素匹配类(是否括号匹配)
- 后缀表达式:栈还可以用于计算后缀表达式(也称为逆波兰表达式)的值。
- 具有LIFO特性的操作
- 其它匹配类问题
6 练习题目
- 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
7 相关题解
暂无相关题解