后缀表达式计算
遇到数值直接放入栈中,遇到操作符将栈顶的两个操作数取出来,然后进行加减乘除操作。注意做除法和减法时,后取出的一个数是被除数和被减数。注意数值中可能有负数。
#include <cstdio>
#include <iostream>
#include <string>
#include <unordered_map>
#include <stack>
#include <algorithm>
using namespace std;
int main(){
int n;
string str;
while(cin>>n){
stack<int> st;
for(int i = 0; i < n; i++){
cin>>str;
if(str.size() == 1 && (str[0] == '+'|| str[0] == '-'|| str[0] == '*'|| str[0] == '/')){
int p = st.top();
st.pop();
int q = st.top();
st.pop();
switch(str[0]){
case '+': st.push(p+q); break;
case '-': st.push(q-p); break;
case '*': st.push(p*q); break;
case '/': st.push(q/p); break;
}
}else{
int t = stoi(str);
st.push(t);
}
}
cout<<st.top()<<endl;
}
return 0;
}