算法-栈和队列:逆波兰表达式
给出逆波兰表达式,求得对应的值。
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int evalRPN(vector<string> s){ //要用vector而不是string,因为不一定是个位数,一个数字可能是多位数
stack<int> st;
for(int i = 0; i < s.size(); i++){
if("+"==s[i] || "-"==s[i] || "*"==s[i] ||"/"==s[i]){
int num1 = st.top();
st.pop();
int num2 = st.top();
st.pop();
if("+"==s[i]){
st.push(num1+num2);
}
else if("-"==s[i]){
st.push(num2-num1);
}
else if("*"==s[i]){
st.push(num1*num2);
}
else{
st.push(num2/num1);
}
}
else {
st.push(stoi(s[i])); //stoi:将string转为int,会判是否越界
}
}
return st.top();
}
int main(){
vector<string> s = {"5","2","-","4","*"};
cout<<evalRPN(s)<<endl;
return 0;
}
|