中缀表达式转后缀表达式代码
时间: 2023-11-20 09:52:46 浏览: 27
中缀表达式转后缀表达式的代码实现如下:
```
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return 0;
}
}
string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";
for (int i = 0; i < infix.length(); i++) {
char c = infix[i];
if (isdigit(c)) {
postfix += c;
} else if (c == '(') {
s.push(c);
} else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
} else {
while (!s.empty() && getPriority(s.top()) >= getPriority(c)) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
string infix = "2+3*4-(5+6)";
string postfix = infixToPostfix(infix);
cout << postfix << endl;
return 0;
}
```
其中,`getPriority`函数用于获取运算符的优先级,`infixToPostfix`函数用于将中缀表达式转换为后缀表达式,`main`函数中的`infix`变量为中缀表达式的字符串表示,`postfix`变量为转换后的后缀表达式的字符串表示。