首页 > 解决方案 > 我正在尝试在java中将中缀更改为后缀,有什么问题?

问题描述

我想用堆栈数据结构将中缀转换为后缀。

在这段代码中,我没有考虑 * 和 / 的情况。


示例输入:10 - ( 3 + 4 ) - 1

正确的输出是:10 3 4 + - 1 -

但我的输出是:10 3 4 + 1 - -


这是我的代码的一部分。我检查了一些我认为是错误的部分。运算符是我创建的堆栈的名称。

public String infix to (String infix) throws ArrayIndexOutOfBoundsException {
    int result=0;
    arr = infix.split(" ");

    String  element = "";
    String postfix="";
    for(int i=0; i<arr.length; i++) {
        element = arr[i];

        if(element.equals("+")||element.equals("-")) {
            operator.push(element);

        }

        else if(element.equals("(")) {
            operator.push(element);

        }
        else if(element.equals(")")) {

            //**As I think, this part might wrong**

            while((!operator.empty())||(!operator.peek().equals("("))){  
                postfix = postfix.concat(operator.pop());
                postfix = postfix.concat(" ");

                if(operator.peek().equals("(")) {
                    operator.pop(); 
                }
                break;
            }   

            }
        else if(isNum(element)){        
            postfix = postfix.concat(element);
            postfix = postfix.concat(" ");          
        }

    }
    while(!operator.empty()) {
        postfix = postfix.concat(operator.pop());
        postfix = postfix.concat(" ");
    }

    return postfix;
}


public static boolean isNum(String s) {
    try {
        Integer.parseInt(s);
        return true;
    }
    catch(NumberFormatException e) {
        return false;
    }
}

谢谢你们。

标签: javapostfix-notation

解决方案


将此更改(!operator.empty())||(!operator.peek().equals("("))(!operator.empty()) && (!operator.peek().equals("("))

while((!operator.empty()) && (!operator.peek().equals("("))){  
                postfix = postfix.concat(operator.pop());
                postfix = postfix.concat(" ");

                if( (!operator.empty()) && (!operator.peek().equals("("))) {
                    break; //invalid
                else
                   operator.pop(); 
                }

            }    

推荐阅读