#include #include using namespace std;

int precedence(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; return 0; }

string infixToPostfix(string infix) { stack 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(); } if (!s.empty()) s.pop(); } else { while (!s.empty() && precedence(c) <= precedence(s.top())) { postfix += s.top(); s.pop(); } s.push(c); } } while (!s.empty()) { postfix += s.top(); s.pop(); } return postfix; }

int main() { string infix; cin >> infix; string postfix = infixToPostfix(infix); cout << postfix << endl; return 0; }

中缀表达式转后缀表达式 (C++ 代码示例)

原文地址: https://www.cveoy.top/t/topic/oiLX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录