表达式转换(2)
续上一条动态,这里最后给出核心的算法:
表达式的转换函数:
// 函数用于将中缀表达式转换为后缀表达式
string infixToPostfix(const string& 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 == '(') {
s.push(c);
}
// 如果是右括号,弹出栈并添加到后缀表达式,直到遇到左括号
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop(); // 弹出左括号
}
// 如果是操作符,处理优先级
else if (isOperator(c)) {
while (!s.empty() && precedence(c) <= precedence(s.top())) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
// 弹出栈中剩余的操作符
while (!s.empty()) {
postfix += s.top();
s.pop();
}
现在对上述代码进行运行,可以看到结果: