Java实现:利用栈实现中缀到后缀的转换

import java.util.Scanner;
import java.util.Stack;


public class MediumStack {


public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 设计以一个方法判断符号的优先级
*/
Scanner in = new Scanner(System.in);
char[] charArr = in.nextLine().toCharArray();
Stack stack = new Stack<>();
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < charArr.length; i++) {
String readStr = String.valueOf(charArr[i]);
if (isOperator(readStr)) {
if (stack.isEmpty()) {
stack.push(readStr);
} else {
if (isMorePrevious(readStr, stack.peek()) || stack.peek().equals("(")) {
stack.push(readStr);
} else if (readStr.equals(")")) {
while (!stack.peek().equals("(")) {
sBuilder.append(stack.pop());
}
stack.pop();


} else {
sBuilder.append(stack.pop());
stack.push(readStr);
}
}


} else {
sBuilder.append(readStr);
}
}
while (!stack.isEmpty()) {
sBuilder.append(stack.pop());
}
System.out.println(sBuilder.toString());
in.close();


}


public static boolean isOperator(String operator) {
String operatorList = "*+-/()";
if (operatorList.contains(operator))
return true;
return false;
}


public static boolean isMorePrevious(String pre, String next) {
return rank(pre) > rank(next) ? true : false;
}


public static int rank(String symbol) {
switch (symbol) {
case "+":
return 1;
case "-":
return 1;
case "*":
return 2;
case "/":
return 2;
case "(":
return 3;
default:
return -1;
}
}
}

你可能感兴趣的:(Java,数据结构)