有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用两个堆栈创建中缀到后缀

我需要使用两个堆栈将中缀计算为后缀表达式。一个堆栈保存所有操作数,另一个堆栈保存所有运算符

  1. 操作数是运算符的第一个或第二个操作数。如果操作员 堆栈为空,或者如果左括号位于堆栈顶部,则操作数为第一个 运算符的操作数。将操作数推送到操作数堆栈上。否则 操作数是运算符的第二个操作数。第一个操作数应位于 操作数堆栈,运算符应位于运算符堆栈的顶部。弹出 堆栈中的第一个操作数和运算符,并形成后缀表达式 表示将运算符应用于其两个操作数。此表达式是一个操作数 可以对其应用另一个运算符,因此将其推送到操作数堆栈上
  2. 右括号标记中缀操作数表达式的结束。匹配的左边 括号应位于运算符堆栈的顶部,后缀操作数表达式 与中缀操作数表达式相对应的表达式应位于操作数堆栈的顶部。 从操作符堆栈中弹出左括号。如果堆栈现在为空,或者如果令牌 堆栈顶部是另一个左括号,即操作数堆栈顶部的操作数 是运算符的第一个操作数,假定整个中缀表达式的结尾为 尚未联系到。在这种情况下,不要做更多的事情。否则,后缀表达式 操作数堆栈顶部是运算符的第二个操作数。第一个操作数 应位于其正下方,并且运算符应位于运算符堆栈的顶部。 从堆栈中弹出操作数和运算符,并形成后缀表达式 表示将运算符应用于其操作数。如上面1所示,按下此表达式 到操作数堆栈上

  3. 要处理运算符或左括号,只需将其推到运算符堆栈上。 容易的 处理完最后一个中缀令牌后,运算符堆栈应为空,并且 操作数堆栈应包含单个后缀表达式。这是后缀 与中缀表达式相对应的表达式

我被下一步该做什么所困扰。这是我到目前为止所拥有的。我想把它分成几部分,这样更容易管理

    /**
 * 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());
        }


    }

共 (0) 个答案