题解 | 后缀序列求值
后缀序列求值
https://www.nowcoder.com/practice/fae66fcaaa284aa98f068f2ed833827f
#include<bits/stdc++.h>
using namespace std;
int main()
{
int sum =0;
stack<int> s1;
stack<char> s2;
string s3;
cin >> s3;
for(int i = 0 ; i < s3.size();i++ ){
if(s3[i] != '+' && s3[i] != '-'){
s1.push(s3[i] - '0');// 入栈
}
else {
s2.push(s3[i]);
}
if(!s2.empty() && s2.top() == '+'){
int a = s1.top();//弹出一个数
s1.pop();//删除一个
int b = s1.top();//弹出一个数字
s1.pop();
sum = b + a;
s1.push(sum);
s2.pop(); // 删除一个运算符
}
if(!s2.empty() && s2.top() == '-'){
int a = s1.top();//弹出一个数
s1.pop();//删除一个
int b = s1.top();//弹出一个数字
s1.pop();
sum = b - a;
s1.push(sum);
s2.pop();//删除一个运算符
}
}
// cout << s1.top() << endl;
cout << s1.top();
}
