中缀转后缀 java_中缀转后缀 java版本实现

1.基于上一播博客https://blog.csdn.net/notears0828/article/details/89047778

2.应用栈,实现将中缀转换成后缀表达是

public class MyExpressionUtil {

/**

* 判断是否是操作符

*/

public static boolean isOperator(char value){

String operatorString = "+-*/()";

return operatorString.indexOf(value) > -1;

}

/**

* 判断操作符的优先级

*/

public static int getPrioraty(char value){

switch (value) {

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

case '(':

case ')':

return 3;

default:

return 0;

}

}

public static String changeExpression(String express){

char[] expressArr = express.toCharArray();

MyStackstack = new MyStack();

StringBuilder sb = new StringBuilder();

for(int i=0;ichar ch = expressArr[i];

switch (ch) {

case '+':

case '-':

case '*':

case '/':

case '(':

if(stack.isEmpty())

stack.push(ch);

else{

char top = stack.pop();//栈顶元素

if(getPrioraty(top)stack.push(top);

stack.push(ch);

}else if(getPrioraty(top)==getPrioraty(ch)) {

sb.append(top);

stack.push(ch);

}else{

while(getPrioraty(top)>getPrioraty(ch)&&!stack.isEmpty()&&top!='('){

sb.append(top);

top = stack.pop();

}

if(getPrioraty(top)==getPrioraty(ch)){

sb.append(top);

stack.push(ch);

}else{

stack.push(top);

stack.push(ch);

}

}

}

break;

case ')':

char top = stack.pop();//栈顶元素

while(top!='('&&!stack.isEmpty()){

sb.append(top);

top = stack.pop();

}

break ;

default:

sb.append(ch);

break;

}

}

while(!stack.isEmpty()) {

sb.append(stack.pop());

}

return sb.toString();

}

}

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页