中缀表达式转后缀表达式 (C++ 代码)
#include
using namespace std;
int main() { string infix; cin >> infix;
string postfix = '';
stack<char> s;
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() && s.top() != '(' && ((c == '+' || c == '-') && (s.top() == '*' || s.top() == '/'))) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
cout << postfix << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/oiMi 著作权归作者所有。请勿转载和采集!