將中綴表達式轉換為後綴表達式需要仔細處理括號。括號的存在給確定正確的運算順序帶來了挑戰。為了解決這個問題,可以採用以下方法:
推入左括號:當遇到左括號時,將其推入運算子堆疊。
處理右括號:遇到右括號時:
以下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(>
透過實作這些步驟,toPostFix()方法可以有效地處理涉及括號的表達式,確保操作順序正確並產生所需的後綴表達式。以上是如何處理中綴到後綴轉換中的括號?的詳細內容。更多資訊請關注PHP中文網其他相關文章!