逆波兰表达式完全实现
控制台输入一则中缀表达式,即我们习惯上的四则运算表达式。首先将其转为逆波兰表达式,是后缀表达式。
然后,计算逆波兰表达式,获得计算结果。
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main() {
char c;//控制台输入char类型数据
vector<string> num;//存储逆波兰表达式
stack<string> sym;//中缀转后缀时,存储符号的栈
stack<int> nums;//四则运算时的数据栈
string nump;//输入int数据时暂存为string
//避免第一位是负号
cin >> c;
if (c == '-'){
string n = {c};
nump.push_back(c);
}
else if (c >= '0' && c <= '9'){
nump.push_back({c});
}
//避免第一位是多余的括号
else {
sym.push("(");
}
//开始中缀转后缀
while (cin >> c){
if (c >= '0' && c <= '9'){
nump.push_back(c);
}
else {
if (!nump.empty()){
num.push_back(nump);
nump.clear();
}
if (c == ')' || c == '}' || c == ']'){
while (sym.top() != "("){
//如果是右括号,那就一直弹栈到左括号也弹出来
//弹出来的符号插入到逆波兰队列中
num.push_back(sym.top());
sym.pop();
}
sym.pop();
}
else if (c == '(' || c == '{' || c == '['){
//如果是左括号,直接插入就行了
sym.push("(");
//避免括号后是负数(-5+这种模式
cin >> c;
if (c >= '0' && c <= '9'){
nump.push_back(c);
}
else if(c == '-') {
string n = {c};
nump.push_back('-');
}
else {
sym.push("(");
}
}
else if (c == '+' || c == '-'){
while (!sym.empty() && sym.top() != "("){
num.push_back(sym.top());
sym.pop();//如果是加号,那么所有符号的优先级都要高于它,弹出
}
sym.push({c});
}
else if (c == '*' || c == '/'){
sym.push({c});//乘法或者除法先入栈再说
}
}
}
if (!nump.empty()){
num.push_back(nump);
}
while (!sym.empty()){
num.push_back(sym.top());
sym.pop();
}
/*
for (int i = 0; i < num.size(); i++){
cout << num[i] << " ";
}
*/
//逆波兰表达式求值
for (int i = 0; i < num.size(); i++){
if ((num[i][0] >= '0' && num[i][0] <= '9') || (num[i][0] == '-' && num[i].size() > 1)){
int a = stoi(num[i]);
nums.push(a);
}
else {
int a = nums.top();
nums.pop();
int b = nums.top();
nums.pop();
if (num[i] == "+"){
nums.push(a+b);
}
else if (num[i] == "-"){
nums.push(b-a);
}
else if (num[i] == "*"){
nums.push(a*b);
}
else {
nums.push(b/a);
}
}
}
cout << nums.top() << endl;
return 0;
}
最后的运行结果如图:
以上。