通关数据结构 day_03 -- 栈
栈
原理
先进后出,可以理解成一个单口的罐子,每次只有两个操作,放进去和拿出来最上面的一个
模板
// tt表示栈顶
int stk[N], tt = 0;
// 向栈顶插入一个数
stk[ ++ tt] = x;
// 从栈顶弹出一个数
tt -- ;
// 栈顶的值
stk[tt];
// 判断栈是否为空
if (tt > 0)
{
}
练习
实现一个栈,栈初始为空,支持四种操作:
push x
– 向栈顶插入一个数 x;pop
– 从栈顶弹出一个数;empty
– 判断栈是否为空;query
– 查询栈顶元素。现在要对栈进行 M 个操作,其中的每个操作 3 和操作 4 都要输出相应的结果。
输入格式
第一行包含整数 M,表示操作次数。
接下来 M 行,每行包含一个操作命令,操作命令为
push x
,pop
,empty
,query
中的一种。输出格式
对于每个
empty
和query
操作都要输出一个查询结果,每个结果占一行。其中,
empty
操作的查询结果为YES
或NO
,query
操作的查询结果为一个整数,表示栈顶元素的值。数据范围
1≤M≤100000,
1≤x≤109
所有操作保证合法。输入样例:
10 push 5 query push 6 pop query pop empty push 4 query empty
输出样例:
5 5 YES 4 NO
#include<iostream>
using namespace std;
const int N = 100010;
int stk[N],tt,m;
// tt 表示栈顶下标
// 插入: stk[++tt] = x;
// 弹出: tt--;
// 判断栈空: if(tt>0) --> 不空
// 栈顶元素: stk[tt];
void init()
{
tt = 0;
}
bool isempty()
{
if(tt==0)
{
return true;
}
return false;
}
void push(int x)
{
stk[++tt] = x;
}
void pop()
{
if(!isempty())
{
tt--;
}
}
int query()
{
cout << stk[tt] << endl;
}
int main()
{
cin >> m;
init();
while(m--)
{
int x;
string op;
cin >> op;
if(op == "push")
{
cin >> x;
push(x);
}else if(op == "pop")
{
pop();
}else if(op == "empty")
{
if(isempty())
{
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
}else if(op == "query")
{
query();
}
}
return 0;
}
给定一个表达式,其中运算符仅包含
+,-,*,/
(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。注意:
- 数据保证给定的表达式合法。
- 题目保证符号
-
只作为减号出现,不会作为负号出现,例如,-1+2
,(2+2)*(-(1+1)+2)
之类表达式均不会出现。- 题目保证表达式中所有数字均为正整数。
- 题目保证表达式在中间计算过程以及结果中,均不超过 231-1。
- 题目中的整除是指向 00 取整,也就是说对于大于 00 的结果向下取整,例如 5/3=15/3=1,对于小于 00 的结果向上取整,例如 5/(1−4)=−15/(1−4)=−1。
- C++和Java中的整除默认是向零取整;Python中的整除
//
默认向下取整,因此Python的eval()
函数中的整除也是向下取整,在本题中不能直接使用。输入格式
共一行,为给定表达式。
输出格式
共一行,为表达式的结果。
数据范围
表达式的长度不超过 105。
输入样例:
(2+2)*(1+1)
输出样例:
8
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
void eval()
{
auto b = num.top(); num.pop();
auto a = num.top(); num.pop();
auto c = op.top(); op.pop();
int x;
if (c == '+') x = a + b;
else if (c == '-') x = a - b;
else if (c == '*') x = a * b;
else x = a / b;
num.push(x);
}
int main()
{
// 定义运算符的优先级
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
string str;
cin >> str;
for (int i = 0; i < str.size(); i ++ )
{
auto c = str[i];
if (isdigit(c)) // 如果当前字符是数字
{
int x = 0, j = i;
while (j < str.size() && isdigit(str[j]))
x = x * 10 + str[j ++ ] - '0';
i = j - 1;
num.push(x);
}
else if (c == '(') op.push(c);
else if (c == ')')
{
while (op.top() != '(') eval();
op.pop();
}
else
{
// 处理优先级
while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval();
op.push(c);
}
}
//操作剩余的计算
while (op.size()) eval();
cout << num.top() << endl;
return 0;
}