#include #include #include using namespace std;

int main() { string infix; cin >> 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 == '+' || c == '-') {
        while (!s.empty() && s.top() != '(') {
            postfix += s.top();
            s.pop();
        }
        s.push(c);
    } else if (c == '*' || c == '/') {
        while (!s.empty() && (s.top() == '*' || s.top() == '/')) {
            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(); // pop the '('
    }
}

while (!s.empty()) {
    postfix += s.top();
    s.pop();
}

cout << postfix << endl;

return 0;

}

中缀表达式转后缀表达式 (C++ 实现)

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

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