主要的规则,一个是遇到) 将 sta中( 之前的符号全部弄到list中。
如果 sta中的符号比新的符号大 或者是 = 都要讲sta中的符号弄到list中 用while
最后将新的符号弄到sta中
package a;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class TransDemo {
public static void main(String[] args) {
String suff = "1+((2+3)*4)-5";
char c = suff.charAt(1);
List<String> li = toList(suff);
System.out.println("li = " + li);
List<String> re = reversePolish(li);
System.out.println("re = " + re);
int res = cal(re);
System.out.println("res = " + res);
}
private static int cal(List<String> re) {
Stack<String> sta = new Stack<>();
for (String s : re) {
if(s.matches("\\d+")){
sta.push(s);
}else {
int n1 = Integer.parseInt(sta.pop());
int n2 = Integer.parseInt(sta.pop());
int res = 0;
switch (s) {
case "+":res = n2+n1;
break;
case "-":res = n2-n1;
break;
case "*":res = n2*n1;
break;
case "/":res = n2/n1;
break;
default:break;
}
sta.push(""+res);
}
}
return Integer.parseInt(sta.pop());
}
private static List<String> reversePolish(List<String> li) {
ArrayList<String> res = new ArrayList<>();
Stack<String> sta = new Stack<>();
for (String e : li) {
if (e.matches("\\d+")) {
res.add(e);
} else if (e.equals("(")) {
sta.push(e);
} else if (e.equals(")")) {//如果遇到)就将前边配对的(消除掉。
while (!sta.peek().equals("(")) {
res.add(sta.pop());//将符号放到list中
}
sta.pop();//将(弹出来
}else{
//栈中的符号>=都要放入li
while (sta.size() != 0 && Operation.get(sta.peek()) >= Operation.get(e)) {//这里因为sta中可能已经了多个符号,
res.add(sta.pop());//将最上面的符号弄出去。while验证第二个
}
sta.push(e);//将当前的符号压如栈。
}
}
//将符号全部放在res 的list中。
while (sta.size() != 0) {
res.add(sta.pop());
}
return res;
}
private static List<String> toList(String suff) {
ArrayList<String> res = new ArrayList<>();//创建res
int i =0;//用于遍历
String whole;//用来保存多位数字
char c ;//用来保存每一个变量
while (i < suff.length()) {
if ((c = suff.charAt(i)) < 48 || (c = suff.charAt(i)) > 57) {//如果不是数
i++;
res.add(c + "");
}else {//就是数
whole ="";
do{
whole+=c;
i++;
}while (i<suff.length()&&((c = suff.charAt(i)) >= 48 && (c = suff.charAt(i)) <= 57));
res.add(whole);
}
}
return res;
}
}
class Operation{
public static final int ADD = 1;
public static final int SUB = 1;
public static final int MUL = 2;
public static final int DIV = 2;
public static int get(String oper) {
int res=0;
switch (oper) {
case "+": res = ADD;break;
case "-": res = SUB;break;
case "*": res = MUL;break;
case "/": res = DIV;break;
default:
System.out.println("without");break;
}
return res;
}
}