【发布时间】:2015-04-29 17:27:08
【问题描述】:
我正在尝试在 Java 中将中缀转换为后缀表达式,但不知何故它没有正确读取它,或者我的队列实现可能有问题。我尝试调试,但看不到哪里出错了。
输入:
2 + 3
4 + 5+6
(7+8) * 9
输出:
2+
4+5
78
正确的输出是:
23+
45+6+
78+9*
这是我的代码:
public int Prior (char c) {
if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return 0;
}
public String convertIn2Post() throws StackException, QueueException{
infix = infix.trim();
for(int i = 0; i < infix.length(); i++) {
if(Character.isDigit(infix.charAt(i))) {
expQueue.enqueue(infix.charAt(i) + "");
}
if (infix.charAt(i) == '(') {
opStack.push(infix.charAt(i) + "");
}
if (infix.charAt(i) == ')') {
while(opStack.peek().equals("(") != true) {
expQueue.enqueue(opStack.pop());
}
opStack.pop();
}
if ( infix.charAt(i) == '+' ||
infix.charAt(i) == '-' ||
infix.charAt(i) == '/' ||
infix.charAt(i) == '*' ) {
if(opStack.isEmpty()){
opStack.push(infix.charAt(i) + "");
}
while(Prior(infix.charAt(i)) <= Prior(opStack.peek().charAt(0))){
expQueue.enqueue(opStack.pop());
if(opStack.isEmpty()){
break;
}
}
}
}
while(!opStack.isEmpty()){
expQueue.enqueue(opStack.pop());
}
for(int y = 0; y < expQueue.size(); y++){
postfix += expQueue.dequeue();
}
return "postfix:: " + postfix;
}
【问题讨论】:
标签: java stack infix-notation