中缀表达式转后缀C++
转成后缀并求值,两个操作都实现了。
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
string intoPost(string infix);//中缀转后缀
int calPost(string post);//后缀做运算
int calculate(int a, int b, char opt);//四则运算
bool isNumber(char s);//判断数字
bool isOpt(char s);//判断运算符
bool isLeft(char s);//判断左括号
bool isRight(char s);//判断右括号
int level(char opt);//获取运算符优先级
int main() {
string infix;//前缀表达式
string post;//后缀表达式
int n = 0;//中缀表达式个数
vector<int> result;//每个中缀表达式运算结果
cin >> n;
for (int i = 0; i < n; i++) {
cin >> infix;
post = intoPost(infix);
result.push_back(calPost(post));
infix.erase(infix.begin(), infix.end());
}
for (int i = 0; i < n; i++)
cout << result[i] << endl;
}
bool isNumber(char s) {
if (s >= '0' && s <= '9')
return true;
else
return false;
}
bool isOpt(char s) {
if (s == '+' || s == '-' || s == '*' || s == '/')
return true;
else
return false;
}
bool isLeft(char s) {
if (s == '(')
return true;
else
return false;
}
bool isRight(char s) {
if (s == ')')
return true;
else
return false;
}
int level(char opt) {
int lev;
if (opt == '+' || opt == '-')
lev = 1;
else if (opt == '*' || opt == '/')
lev = 2;
else
lev = 0;
return lev;
}
int calculate(int a, int b, char opt) {
int sum;
if (opt == '+')
sum = a + b;
else if (opt == '-')
sum = a - b;
else if (opt == '*')
sum = a * b;
else if (opt == '/')
sum = a / b;
else
throw - 1;
return sum;
}
string intoPost(string infix) {
string post;
stack<char> s;//符号栈
for (int i = 0; i < infix.length(); i++) {
if (isNumber(infix[i])) {
post += infix[i];
if (!isNumber(infix[i + 1]))
post += '#';
}
else if (isLeft(infix[i])) {
s.push(infix[i]);
}
else if (isRight(infix[i])) {
while (!isLeft(s.top())) {
post += s.top();
s.pop();
}
s.pop();//弹出栈顶左括号
}
else if (isOpt(infix[i])) {
if (s.empty())
s.push(infix[i]);
else {
while (s.top()!='('&&level(s.top()) >= level(infix[i])) {
post += s.top();
s.pop();
if (s.empty())
break;
}
s.push(infix[i]);
}
}
else
throw - 1;
}
while (!s.empty()) {//把符号栈清空
post += s.top();
s.pop();
}
return post;
}
int calPost(string post) {
stack<int> num;//储存运算中间值
for (int i = 0; i < post.length(); i++) {
if (isNumber(post[i])) {
int sum = 0;
while (isNumber(post[i])) {
sum = sum * 10 + post[i]-'0';
i++;
}
num.push(sum);
}
else if (isOpt(post[i])) {
int b = num.top(); num.pop();
int a = num.top(); num.pop();
num.push(calculate(a, b, post[i]));
}
}
return num.top();
}