逆波兰式转换
1、输入:算术表达式(字符串形式数据)
2、输出:逆波兰式以及计算结果
转换过程如下所示:
栈底放‘#’,从左至右逐字读取中缀式:
a.当当前字符为数字时,直接输出;
b.当当前字符为"(“时,将其压栈;
c.当当前字符为”)“时,则弹出堆栈中最上的”(“之前的所有运算符并输出,然后删除堆栈中的”(" ;
d.当当前字符为运算符时,则依次弹出堆栈中优先级大于等于当前运算符的(到"(“之前为止),输出,再将当前运算符压栈;
e.当为”#"时,弹出所有栈中的内容输出
//
// main.cpp
// 逆波兰式
//
// Created by Ahu-06 on 2019/2/24.
// Copyright © 2019年 Ahu-06. All rights reserved.
//
#include <stack>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int precede(char a) {
switch (a)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '#':
return 0;
default:
return 0;
}
}
bool comparePrecde(char a,char b) { //前表达式中的元素 后栈中的元素
int pre_a = precede(a);
int pre_b = precede(b);
if (pre_a > pre_b) {
return true;
}
else {
return false;
}
}
int main() {
stack<char> numStack; //用来存储数字
stack<char> exprStack; //用来存储表达式
stack<char> tempStack; //暂时存储
stack<float> resStack; //用来存储计算结果
vector<char> opVec; //正序输出
exprStack.push('#');
string buffer; //用来读取中缀表达式
cout<<"输入算术表达式:"<<endl;
cin >> buffer;
for (int i = 0; i < buffer.size(); ++i) { //数字和运算符分离
if (isdigit(buffer[i])) {
numStack.push(buffer[i]);
}
else {
while (!comparePrecde(buffer[i], exprStack.top())) {
numStack.push(exprStack.top());
exprStack.pop();
}
exprStack.push(buffer[i]);
}
}
while (exprStack.top() != '#') { //剩余的元素压入栈
numStack.push(exprStack.top());
exprStack.pop();
}
while (!numStack.empty()) {
opVec.push_back(numStack.top());
tempStack.push(numStack.top());
numStack.pop();
}
reverse(opVec.begin(), opVec.end()); //输出逆波兰式列
cout<<"逆波兰式为:"<<endl;
for (auto x : opVec) {
cout << x<<" ";
}
cout << endl;
//计算结果
while (!tempStack.empty()) {
if (isdigit(tempStack.top())) {
resStack.push((float)(tempStack.top() - '0')); //char to int
tempStack.pop();
}
else {
char expr = tempStack.top();
tempStack.pop();
float a = resStack.top();
resStack.pop();
float b = resStack.top();
resStack.pop();
switch (expr)
{
case'+':
resStack.push(b + a);
break;
case'-':
resStack.push(b - a);
break;
case'*':
resStack.push(b * a);
break;
case'/':
resStack.push(b / a);
break;
}
}
}
cout<<"计算结果为:"<<endl;
cout << resStack.top() << endl; //输出结果
return 0;
}
运行结果