数据结构—中缀表达式转后缀表达式并计算出结果
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <vector>
#include <cctype>
using namespace std;
int precedence(char op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
vector<string> infixToPostfix(string infix) {
stack<char> operators;
vector<string> postfix;
string operand;
for (int i = 0; i < infix.length(); i++) {
if (isdigit(infix[i]) || (infix[i] == '-' && (i == 0 || isOperator(infix[i - 1]) || infix[i - 1] == '('))) {
operand += infix[i];
} else {
if (!operand.empty()) {
postfix.push_back(operand);
operand.clear();
}
if (infix[i] == '(') {
operators.push(infix[i]);
} else if (infix[i] == ')') {
while (!operators.empty() && operators.top() != '(') {
postfix.push_back(string(1, operators.top()));
operators.pop();
}
if (!operators.empty() && operators.top() == '(') {
operators.pop();
}
} else {
while (!operators.empty() && precedence(infix[i]) <= precedence(operators.top()) && operators.top() != '(') {
postfix.push_back(string(1, operators.top()));
operators.pop();
}
operators.push(infix[i]);
}
}
}
if (!operand.empty()) {
postfix.push_back(operand);
}
while (!operators.empty()) {
postfix.push_back(string(1, operators.top()));
operators.pop();
}
return postfix;
}
int evaluatePostfix(vector<string> postfix) {
stack<int> st;
for (const auto &token : postfix) {
if (isdigit(token[0]) || (token.length() > 1 && token[0] == '-')) {
st.push(stoi(token));
} else {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
if (token == "+") st.push(a + b);
else if (token == "-") st.push(a - b);
else if (token == "*") st.push(a * b);
else if (token == "/") st.push(a / b);
}
}
return st.top();
}
int main() {
string infix;
cout << "请输入中缀表达式(不带空格):";
cin >> infix;
vector<string> postfix = infixToPostfix(infix);
cout << "后缀表达式为:";
for (const auto &token : postfix) {
cout << token << " ";
}
cout << endl;
int result = evaluatePostfix(postfix);
cout << "计算结果为:" << result << endl;
return 0;
}