java - 我正在尝试在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;
}
}
谢谢你们。
解决方案
将此更改(!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();
}
}
推荐阅读
- python - 将字典与字典映射合并,并组合值
- c++ - codeforces 上可用的编码问题的解决方案链接在下面,称为 Presents 问题 -136A
- reactjs - axios post出现401(未经授权)错误
- python - 编码大量分类特征的最佳方法是什么?
- git - .gitconfig 中针对两个不同 URL 的 Git lfs 配置
- memory-management - 如果 CPU 正在处理相应的内存请求,如何保证该内存页不会被驱逐?
- php - 如何根据 1.1.0 -> 1.1.1->1.1.2 等版本在 mysql 查询中排序?
- python-3.x - 是否有一个模块可以在浏览器中通过 snap 辅助打开两个 URL?
- java - 如何在不使用终止语句的情况下终止 Java 流?
- github - 如何为与 github api 匹配某个字符串的存储库获取 N 次提交?