热门

最新

红包

立Flag

投票

同城

我的

发布
weixin_50101791
陨落的天才2
2 年前
trueweixin_50101791

表达式转换(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();
}

现在对上述代码进行运行,可以看到结果:

CSDN App 扫码分享
分享
评论
1
打赏
  • 复制链接
  • 举报
下一条动态
立即登录