中缀表达式转后缀c++要求代码简化
以下是一个简化的C++代码实现中缀表达式转后缀的算法:
#include <iostream>
#include <stack>
#include <string>
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int getPriority(char c) {
if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
}
return 0;
}
std::string infixToPostfix(const std::string& infix) {
std::string postfix;
std::stack<char> operators;
for (char c : infix) {
if (isOperator(c)) {
while (!operators.empty() && isOperator(operators.top()) && getPriority(operators.top()) >= getPriority(c)) {
postfix += operators.top();
operators.pop();
}
operators.push(c);
} else if (c == '(') {
operators.push(c);
} else if (c == ')') {
while (!operators.empty() && operators.top() != '(') {
postfix += operators.top();
operators.pop();
}
operators.pop();
} else {
postfix += c;
}
}
while (!operators.empty()) {
postfix += operators.top();
operators.pop();
}
return postfix;
}
int main() {
std::string infix = "3+4*2/(1-5)";
std::string postfix = infixToPostfix(infix);
std::cout << "Infix expression: " << infix << std::endl;
std::cout << "Postfix expression: " << postfix << std::endl;
return 0;
}
这个代码实现了一个函数infixToPostfix,接受一个中缀表达式字符串作为参数,并返回对应的后缀表达式字符串。在这个函数中,我们使用一个栈来存储运算符,并遍历中缀表达式的每个字符。如果遇到数字,直接将其添加到后缀表达式字符串中;如果遇到运算符,则将栈中优先级较高或相等的运算符弹出,并添加到后缀表达式字符串中,然后将当前运算符压入栈中;如果遇到左括号,则将其压入栈中;如果遇到右括号,则将栈中的运算符弹出,并添加到后缀表达式字符串中,直到遇到左括号为止。最后,将栈中剩余的运算符弹出,并添加到后缀表达式字符串中。
在main函数中,我们可以调用infixToPostfix函数来将一个中缀表达式转换为后缀表达式,并输出结果。例如,对于输入的中缀表达式"3+42/(1-5)",输出的后缀表达式为"34215-/+"
原文地址: https://www.cveoy.top/t/topic/ibB2 著作权归作者所有。请勿转载和采集!