将中缀表达式转换为后缀表达式需要仔细处理括号。括号的存在给确定正确的运算顺序带来了挑战。为了解决这个问题,可以采用以下方法:
推入左括号:当遇到左括号时,将其推入运算符堆栈。
处理右括号:遇到右括号时:
以下 Java 代码演示了如何修改 toPostFix() 方法来处理括号:
public String toPostFix() { StringBuilder postfixstr = new StringBuilder(); Stack<Token> in_fix = new Stack<>(); Stack<Token> post_fix = new Stack<>(); for (int i = tokens.length - 1; i >= 0; i--) { t = new Token(tokens[i]); in_fix.push(t); } //there are still tokens to process while (!in_fix.empty()) { // is a number if (in_fix.peek().type == 1) { postfixstr.append(in_fix.pop().toString()); } // is an operator and the stack is empty else if (in_fix.peek().type == 3 && post_fix.empty()) { post_fix.push(in_fix.pop()); } // is an operator that has higher priority than the operator on the stack else if (in_fix.peek().type == 3 && in_fix.peek().isOperator() > post_fix.peek().isOperator()) { post_fix.push(in_fix.pop()); } // is an operator that has lower priority than the operator on the stack else if (in_fix.peek().type == 3 && in_fix.peek().isOperator() <= post_fix.peek().isOperator()) { postfixstr.append(post_fix.pop()); post_fix.push(in_fix.pop()); } // opening ( else if (in_fix.peek().type == 4) { post_fix.push(in_fix.pop()); } // closing ) else if(in_fix.peek().type == 5){ while(!(post_fix.isEmpty() || post_fix.peek().type == 4)){ postfixstr.append(post_fix.pop()); } if (post_fix.isEmpty()) ; // ERROR - unmatched ) else post_fix.pop(); // pop the ( in_fix.pop(); // pop the ) } //puts the rest of the stack onto the output string if (in_fix.empty()) { while (!post_fix.empty()) { postfixstr.append(post_fix.pop()); } } } return postfixstr.toString(); }
通过实现这些步骤,toPostFix()方法可以有效地处理涉及括号的表达式,确保操作顺序正确并生成所需的后缀表达式。
以上是如何处理中缀到后缀转换中的括号?的详细内容。更多信息请关注PHP中文网其他相关文章!