後綴表達式計算
遇到數值直接放入棧中,遇到操作符將棧頂的兩個操作數取出來,然後進行加減乘除操作。注意做除法和減法時,後取出的一個數是被除數和被減數。注意數值中可能有負數。
#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;
}