【发布时间】:2020-11-11 05:53:52
【问题描述】:
如果我有这个字符串中缀表达式 2*4+3-15/2 并且我想输出后缀表达式而不考虑像这样的操作的优先级
2 4 * 3 + 15 - 2 /
我需要在此代码示例中进行哪些修改才能“删除”该优先级。我从 geeksforgeeks https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/ 那里获取了这段代码。我觉得改变来满足我想要的有点困难。我应该从哪里开始?谢谢。
当前代码给了我这个输出:24*3+152/-
private int Prec(String ch)
{
switch (ch)
{
case "+":
case "-":
return 1;
case "*":
case "/":
return 2;
case "^":
return 3;
}
return -1;
}
private boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
private String infixToPostfix(String infixExpression){
// initializing empty String for result
StringBuilder postfixExpression = new StringBuilder(new String(""));
String[] infixExp = infixExpression.split(" ");
// initializing empty stack
Stack<String> stack = new Stack<>();
for (String token : infixExp) {
System.out.println(token+" ");
// If the scanned character is an operand, add it to output.
if (isNumeric(token))
postfixExpression.append(token);
// If the scanned character is an '(', push it to the stack.
else if (token.equals("("))
stack.push(token);
// If the scanned character is an ')', pop and output from the stack
// until an '(' is encountered.
else if (token.equals(")")) {
while (!stack.isEmpty() && !stack.peek().equals("("))
postfixExpression.append(stack.pop());
if (!stack.isEmpty() && !stack.peek().equals("("))
return "Invalid Expression"; // invalid expression
else
stack.pop();
} else // an operator is encountered
{
while (!stack.isEmpty() && Prec(token) <= Prec(stack.peek())) {
if (stack.peek().equals("("))
return "Invalid Expression";
postfixExpression.append(stack.pop());
}
stack.push(token);
}
}
// pop all the operators from the stack
while (!stack.isEmpty()){
if(stack.peek().equals("("))
return "Invalid Expression";
postfixExpression.append(stack.pop());
}
System.out.println(postfixExpression);
return postfixExpression.toString();
}
【问题讨论】:
-
如果可能,
Binary Tree数据类型可能更适合这种情况。 -
只需在
Prec()方法中给每个操作员相同的优先级。 -
@MarquisofLorne 哦,天哪,你是对的,就这么简单,你可以写一个答案,这样我就可以绿色检查你了 :) 谢谢
标签: java algorithm stack postfix-notation infix-notation