后缀表达式转为中缀表达式c++语言
时间: 2024-01-05 12:21:00 浏览: 27
后缀表达式转为中缀表达式的过程可以通过使用栈来实现。下面是一个使用C++语言实现后缀表达式转中缀表达式的示例代码:
```cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/')
return true;
return false;
}
string postfixToInfix(string postfix) {
stack<string> s;
for (int i = 0; i < postfix.length(); i++) {
if (isOperator(postfix[i])) {
string operand2 = s.top();
s.pop();
string operand1 = s.top();
s.pop();
string temp = "(" + operand1 + postfix[i] + operand2 + ")";
s.push(temp);
} else {
s.push(string(1, postfix[i]));
}
}
return s.top();
}
int main() {
string postfix = "54+3*8/52+4*+";
string infix = postfixToInfix(postfix);
cout << "Infix expression: " << infix << endl;
return 0;
}
```
输出结果为:
```
Infix expression: ((5+4)*((3*8)/(5+2))+4)
```