#include"iostream"
#include"stdlib.h"
#include"string "
#include"vector"
#include"stack"
using namespace std;
/*
此代码为后缀表达式的计算
力扣:150. 逆波兰表达式求值
*/
int evalRPN(vector<string>& tokens) {
stack<int> st; //定义一个栈,用于数字的入栈和存放运算的结果
for (auto ch : tokens ) //遍历表达式
{
if(ch=="+"|| ch == "-" || ch == "*" || ch == "/" ) //遇到运算符就计算
{
int b = st.top(); //先出栈的位于表达式右边如:a+b
st.pop();
int a = st.top();
st.pop();
if (ch == "+") st.push(a + b);
if (ch == "-") st.push(a - b);
if (ch == "*") st.push(a * b);
if (ch == "/") st.push(a / b);
}
else{ //数字就入栈
st.push(stoi(ch)); //stoi 将字符串转化为数字,默认转化为十进制,需要包含string头文件
}
}
return st.top();
}
int main() {
vector<string> tokens = { "10","6","9","3","+","-11","*","/","*","17","+","5","+" };
cout << "res:"<<evalRPN(tokens);
cout << endl;
system("pause");
return 0;
}
力扣:150. 逆波兰表达式求值
最新推荐文章于 2024-02-21 22:41:40 发布