您的位置:首页 > 编程语言 > Java开发

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

2017-09-14 14:21 323 查看
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<String> 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;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息