828. 模拟栈
输入样例:
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;
int main()
{
int n;
cin>>n;
while(n--)
{
string op;
int x;
cin>>op;
if(op=="push")
{
cin>>x;
stk[++tt]=x;
}
else if(op=="pop") tt--;
//tt!=0则栈不空,输出NO
else if(op=="empty") cout << (tt ? "NO" : "YES") << endl;
else cout << stk[tt] << endl;
}
}
3302. 表达式求值
参考自https://www.acwing.com/solution/content/40978/
# include <iostream>
# include <stack>
# include <string>
# include <unordered_map>
using namespace std;
stack <int> num;
stack <char> op;
//定义操作符的优先级表 pr(prior)
unordered_map<char,int> pr{ {'+',1}, {'-',1}, {'*',2}, {'/',2} };
//求值函数,取出num的最后两个数和op的栈顶进行计算
// a / b ,先取出b, 后取出a
void eval()
{
int b = num.top(); num.pop();
int a = num.top(); num.pop();
char p = op.top(); op.pop();
int res = 0;
if(p=='+') res = a + b;
else if(p=='-') res = a - b;
else if(p=='*') res = a * b;
else if(p=='/') res = a / b;
num.push(res);
}
int main()
{
string s;
cin>>s;
for(int i = 0;i<s.size();i++)
{
if(isdigit(s[i]))
{
int j=i,x=0;
while(j<s.size()&&isdigit(s[j]))
{
x = x * 10 + s[j] - '0';
j++;
}
num.push(x);
i = j-1;//将i跳转到最后一位数字处
}
else if(s[i]=='(') op.push(s[i]);
else if(s[i]==')')
{
while(op.top()!='(') eval();
op.pop(); //弹出op的(
}
else
{
while(op.size()&&pr[op.top()]>=pr[s[i]]) eval();
op.push(s[i]);
}
}
while(op.size()) eval();
cout<<num.top()<<endl;
}
易错点:
- 忘记给x赋初值0
- s[i]为右括号时应计算直至op.top()为左括号,才停止运算【将op.top()写错为s[i]会出错!】