#include #include #include

using namespace std;

bool isOperator(char c) { return (c == '+' || c == '-' || c == '*' || c == '/'); }

int getPrecedence(char op) { if (op == '+' || op == '-') { return 1; } else if (op == '*' || op == '/') { return 2; } else { 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 (isOperator(c)) {
        while (!s.empty() && isOperator(s.top()) && getPrecedence(s.top()) >= getPrecedence(c)) {
            postfix += s.top();
            s.pop();
        }
        s.push(c);
    } else if (c == '(') {
        s.push(c);
    } else if (c == ')') {
        while (!s.empty() && s.top() != '(') {
            postfix += s.top();
            s.pop();
        }
        s.pop();
    }
}

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/oiL7 著作权归作者所有。请勿转载和采集!

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