我正在写一段代码,用于将硬件赋值的中缀转换为后缀。我已经调试过了,但我似乎搞不懂为什么当它弹出堆栈时,它会返回'(‘而不是'+’
StackInterface<Character> stack = new ArrayStack<Character>();
String postfix = "";
int length = infxEx.length();
for(int i =0; i != length; ++i){
char oneChar =infxEx.charAt(i);
if(oneChar == '('){
stack.push(oneChar);
}else
if(oneChar == '*' || oneChar == '/'|| oneChar == '%'|| oneChar == '+' || oneChar == '-'){
stack.push(oneChar);
//error checking input is int
}
else if(oneChar == ')'){
while (stack.pop() != '(' && !stack.empty()){
char popoff = stack.pop();
postfix = postfix + popoff;
}
}谢谢!
发布于 2016-03-06 10:19:29
在处理到达)的循环中,对于您检查的每个元素,从堆栈中弹出两次(第一次在while条件中检查stack.pop() != '(',第二次在循环体中获取popoff,因此您将丢失大约一半的字符;因为这是通过到达主循环中的)触发的,并且因为您忽略了任何不是运算符的东西(因此(a + b)的堆栈将包含(+,并且您将在检查(时剥离+,这意味着您将在while循环体内的后缀中添加(,并在堆栈为空时终止循环。
使用窥视操作来查看堆栈的顶部,而不实际删除while循环条件中的值来解决该问题,如果在中缀表达式中接受运算符以外的标记,则还需要一个else子句来处理这种情况。
https://stackoverflow.com/questions/35821284
复制相似问题