中缀表达式转后缀c++要求代码最简化
下面是一个简化的C++代码,用于将中缀表达式转换为后缀表达式:
#include <iostream>
#include <stack>
#include <string>
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int getPrecedence(char c) {
if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
}
return 0;
}
std::string infixToPostfix(const std::string& expression) {
std::string postfix = "";
std::stack<char> operatorStack;
for (char c : expression) {
if (isOperator(c)) {
while (!operatorStack.empty() && operatorStack.top() != '(' && getPrecedence(operatorStack.top()) >= getPrecedence(c)) {
postfix += operatorStack.top();
operatorStack.pop();
}
operatorStack.push(c);
} else if (c == '(') {
operatorStack.push(c);
} else if (c == ')') {
while (!operatorStack.empty() && operatorStack.top() != '(') {
postfix += operatorStack.top();
operatorStack.pop();
}
if (!operatorStack.empty() && operatorStack.top() == '(') {
operatorStack.pop();
}
} else {
postfix += c;
}
}
while (!operatorStack.empty()) {
postfix += operatorStack.top();
operatorStack.pop();
}
return postfix;
}
int main() {
std::string expression;
std::cout << "Enter an infix expression: ";
std::cin >> expression;
std::string postfix = infixToPostfix(expression);
std::cout << "Postfix expression: " << postfix << std::endl;
return 0;
}
这个代码实现了一个infixToPostfix函数,它接受一个中缀表达式作为输入,并返回一个后缀表达式。它使用了一个操作符栈来转换表达式。在主函数中,用户被要求输入一个中缀表达式,并打印出相应的后缀表达式。
注意:这个代码只支持基本的四则运算符。如果需要支持其他运算符,可以在isOperator和getPrecedence函数中进行相应的修改
原文地址: https://www.cveoy.top/t/topic/ibB7 著作权归作者所有。请勿转载和采集!