中缀表达式转后缀表达式一图秒杀
发表时间:2020-10-19
发布人:葵宇科技
浏览次数:37
大年夜功课请求写个中缀表达式转后缀表达式,结不雅发明视频琅绫擎给的解法是个错的,网上找了一大年夜堆,各类说法都有,公说公有理婆说婆有理,花里胡哨的,看着也复杂的一匹,说的话旁敲侧击的,看几下就开端看不懂了,研究到凌晨终于画了一张:秒杀大年夜图,图是基于调剂场算法(Shunting-Yard algorithm)的流程图,可以说是清楚清楚明了,就照着图无脑撸代码就完事了
代码如下(仅参考,建议照样看图本身敲的舒畅):
public Queue infixToPostfix(Queue infix) {
Stack stack = new Stack();
Queue postfix = new Queue();
Boolean backtoRoot = false;
while (!infix.isEmpty()){
backtoRoot = false;
Data data = infix.poll();
if (data.type == Type.OPERATOR || data.type == Type.PAREN){
if ("+-*/".contains(data.getOperator() )){
while (!stack.isEmpty()) { //Stack is not empty
Token top = stack.peek();
if (("+-(".contains(top.getOperator()) & "/*".contains(data.getOperator())) | ((top.getOperator().equals("(")) & "-+".contains(data.getOperator() ))){ //栈顶元素优先级低于本身
stack.push(data);
backtoRoot = true;
break;
}else {
postfix.offer(stack.pop());
continue;
}
}
if (backtoRoot){
continue;
}
// Stack is empty
if (stack.isEmpty()){
stack.push(data);
continue;
}
continue;
}
if ((data.getOperator().equals("(") )){
stack.push(data);
continue;
}
if (")".contains(data.getOperator() )){
while (!stack.isEmpty() ){
if (stack.peek().getOperator().equals("(")) {
stack.pop();
break;
}
postfix.offer(stack.pop());
}
continue;
}
}
if (data.type == Type.OPERAND){
postfix.offer(data);
continue;
}
}
while (!stack.isEmpty()){
postfix.offer(stack.pop());
}
return postfix;
}