C++实现中缀表达式转前缀、后缀表达式输出不符合预期的问题排查
代码现存问题
- 操作数判断逻辑完全写反
- 数字判断原条件为
ch <= '0' && ch <= '9',永远无法匹配数字字符,正确逻辑需要满足字符ASCII码落在'0'到'9'区间内,即ch >= '0' && ch <= '9' - 大写字母判断原条件为
ch <= 'A' && ch >= 'Z',由于'A'的ASCII码小于'Z',该条件永远不可能成立,需修正为ch >= 'A' && ch <= 'Z' - 可直接使用
<cctype>提供的isalnum()工具函数判断数字/字母操作数,避免手写ASCII区间判断的低级逻辑错误
- 数字判断原条件为
- 输出顺序颠倒
原代码先输出前缀表达式、再输出后缀表达式,和题目要求的输出顺序(第一行后缀、第二行前缀)完全相反 - 健壮性不足
原precedence()函数没有兼容括号场景,虽然后续逻辑用栈顶判断避开了括号,但如果函数被意外传入括号参数会返回错误的优先级值;另外原循环判断没有做栈空校验,在边界场景下可能出现栈空访问崩溃
关于后缀表达式不包含括号的实现说明
这套基于双栈的转换逻辑,圆括号仅作为优先级调整标记存放在运算符栈中,永远不会被拼接进操作数的结果串里。只要修复现有逻辑bug,生成的后缀表达式天然不会携带括号,不需要额外做括号删除操作。
修改后的可运行代码
#include <cstring> #include <cctype> #include <iostream> #include <stack> #include <string> using namespace std; int precedence(char ch) { if (ch == '+' || ch == '-') { return 1; } else if (ch == '*' || ch == '/') { return 2; } // 括号优先级最低,避免被误弹出 return 0; } void preProcess(stack<string> &preS, char op) { string val2 = preS.top(); preS.pop(); string val1 = preS.top(); preS.pop(); // 前缀格式:运算符 + 左操作数 + 右操作数 preS.push(op + val1 + val2); } void postProcess(stack<string> &postS, char op) { string val2 = postS.top(); postS.pop(); string val1 = postS.top(); postS.pop(); // 后缀格式:左操作数 + 右操作数 + 运算符,全程不拼接括号 postS.push(val1 + val2 + op); } void prefixPostfixConversion(string expr) { stack<string> preS; stack<string> postS; stack<char> opS; for (int i = 0; i < expr.length(); ++i) { char ch = expr.at(i); if (ch == '(') { opS.push(ch); } else if (isalnum(ch)) { string s(1, ch); preS.push(s); postS.push(s); } else if (ch == ')') { while (!opS.empty() && opS.top() != '(') { char op = opS.top(); opS.pop(); preProcess(preS, op); postProcess(postS, op); } if (!opS.empty()) opS.pop(); } else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') { // 左结合规则:当前运算符优先级小于等于栈顶优先级时,持续弹出栈顶运算符 while (!opS.empty() && precedence(ch) <= precedence(opS.top())) { char op = opS.top(); opS.pop(); preProcess(preS, op); postProcess(postS, op); } opS.push(ch); } } while (!opS.empty()) { char op = opS.top(); opS.pop(); preProcess(preS, op); postProcess(postS, op); } // 调整为题目要求的输出顺序:先输出后缀,再输出前缀 cout << postS.top() << endl; cout << preS.top() << endl; } int main() { string expr; getline(cin, expr); prefixPostfixConversion(expr); return 0; }
运行验证
输入示例a*(b-c+d)/e,程序输出完全匹配要求:
abc-d+*e/ /*a+-bcde
内容的提问来源于stack exchange,提问作者Kushagra
相关产品推荐
相关产品推荐

