Java 如何使用两个堆栈创建中缀到后缀
我需要使用两个堆栈将中缀计算为后缀表达式。一个堆栈保存所有操作数,另一个堆栈保存所有运算符Java 如何使用两个堆栈创建中缀到后缀,java,data-structures,infix-notation,Java,Data Structures,Infix Notation,我需要使用两个堆栈将中缀计算为后缀表达式。一个堆栈保存所有操作数,另一个堆栈保存所有运算符 操作数是运算符的第一个或第二个操作数。如果操作员 堆栈为空,或者如果左括号位于堆栈顶部,则操作数为第一个 运算符的操作数。将操作数推送到操作数堆栈上。否则 操作数是运算符的第二个操作数。第一个操作数应位于 操作数堆栈,运算符应位于运算符堆栈的顶部。弹出 堆栈中的第一个操作数和运算符,并形成后缀表达式 表示将运算符应用于其两个操作数。此表达式是一个操作数 可以对其应用另一个运算符,因此将其推送到操作数堆栈上
/**
* Evaluates the specified postfix expression. If an operand is encountered,
* it is pushed onto the stack. If an operator is encountered, two operands
* are popped, the operation is evaluated, and the result is pushed onto the
* stack.
*
* @param expr
* string representation of a postfix expression
* @return value of the given expression
*/
public String evaluate(String expr) {
// A variable to hold the resulting postfix expression
String result;
// A variable to hold individual tokens in the infix expression
String token;
// Scanner to read the users input expression
Scanner parser = new Scanner(expr);
// Variables to hold the first and second operands
String op1, op2;
// Reading the input one character at a time
while (parser.hasNext()) {
token = parser.next();
// Performing postfix calculations
// Pushing values on the stacks
if (token.equals("(")) {
operatorStack.push(token);
}
else if (!isOperator(token)){
operandStack.push(token);
}
else{
operatorStack.push(token);
}
//Part 1
if (operatorStack.isEmpty() || operatorStack.peek().equals("(")){
operandStack.push(token);
}
else{
op2 = (operandStack.peek());
}
}
默认情况下,扫描程序在空白处标记。。。如果
((7*2)+5)/2
作为3个令牌返回,您会遇到问题。我知道输入之间的空格是我计划要做的