用栈实现中缀表达式转后缀表达式c++
时间: 2023-12-22 19:04:25 浏览: 108
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
}
return 0;
}
string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";
for (char &c : infix) {
if (isalnum(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 = "1+(2-3)*4+10/5";
string postfix = infixToPostfix(infix);
cout << "The postfix expression is: " << postfix << endl;
return 0;
}
```
阅读全文