0

こんにちは、私は Java でいくつかのスタックを練習しており、スタックに関する問題を解決しようとしています。後置表記を取り、それを中置に変換するメソッドを作成しようとしていました。これは私がこれまでに持っているものです:

`
public void convertion() {
        Stack<Integer> stack;          // For evaluating the expression.
        stack = new Stack<Integer>();  // Make a new, empty stack.

        Scanner scan = new Scanner(postfix);

        int t1, t2 = 0;     //Operands

        boolean check = false;


        while (scan.hasNext() && !check) {
            if (scan.hasNextInt()) {
                int operand = scan.nextInt();
                stack.push(operand);
            } else {
                char operator = scan.next().charAt(0);
                try {

                        while(stack.)


                } catch (EmptyStackException e) {
                    answer = "Malformed postfix expression";
                    check = true;
                }

            }
        }
        scan.close();
        try {
            answer = "" + stack.pop();
        } catch (EmptyStackException e) {
            answer = "Malformed postfix expression";
        }
    }
`

私が問題を抱えている部分は、試してみる部分に何を置くべきかということです。基本的には、見つけたすべての数値をスタックにプッシュしますが、演算子を見つけたら、2 つのオペランドと演算子をマージするにはどうすればよいですか。

ありがとう。

4

1 に答える 1

-1

上位 2 つのスタック要素をポップし、それらに対して適切な操作を実行してから、結果をプッシュ バックします。

try {
    int o1 = stack.pop().intValue();
    int o2 = stack.pop().intValue();
    switch (operator) {
        case '+': stack.push(new Integer(o1 + o2));
                  break;
        case '-': stack.push(new Integer(o1 - o2));
                  break;
        ...
    }
}
catch (EmptyStackException e) {
    ...
于 2013-04-06T02:43:49.723 に答える