中缀转后缀表达式树c++
时间: 2023-08-03 16:57:59 浏览: 54
你可以使用栈来将中缀表达式转换为后缀表达式。下面是一个示例的C++代码:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 判断运算符的优先级
int precedence(char op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
// 将中缀表达式转换为后缀表达式
string infixToPostfix(string infix) {
string postfix;
stack<char> opStack;
for (int i = 0; i < infix.length(); i++) {
char ch = infix[i];
// 如果是操作数,直接添加到后缀表达式
if (isalnum(ch)) {
postfix += ch;
}
// 如果是左括号,入栈
else if (ch == '(') {
opStack.push(ch);
}
// 如果是右括号,将栈中的运算符弹出,直到遇到左括号
else if (ch == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfix += opStack.top();
opStack.pop();
}
// 弹出左括号
opStack.pop();
}
// 如果是运算符
else {
while (!opStack.empty() && precedence(opStack.top()) >= precedence(ch)) {
postfix += opStack.top();
opStack.pop();
}
// 将当前运算符入栈
opStack.push(ch);
}
}
// 将栈中剩余的运算符加入后缀表达式
while (!opStack.empty()) {
postfix += opStack.top();
opStack.pop();
}
return postfix;
}
int main() {
string infixExpression;
cout << "Enter an infix expression: ";
getline(cin, infixExpression);
string postfixExpression = infixToPostfix(infixExpression);
cout << "Postfix expression: " << postfixExpression << endl;
return 0;
}
```
你可以根据需要提供中缀表达式,并使用上述代码进行转换。它将输出对应的后缀表达式。希望能帮到你!