資料結構與演算法Java版--逆波蘭式
阿新 • • 發佈:2021-02-02
本系列部落格源自學習《尚矽谷資料結構與演算法》的學習隨筆。
package test.learn.algorithm.PolandNotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class poland {
public static void main(String[] args) {
String expression = "4 5 * 8 - 60 + 8 2 / +" ;
List<String> list = getList(expression);
System.out.println(list);
System.out.println(calculate(list));
}
//將逆波蘭式傳入一個數組之中
public static List<String> getList(String express){
String [] spilt = express.split(" ");
List<String> list = new ArrayList<String>();
for (String s : spilt) {
list.add(s);
}
//System.out.println(list);
return list;
}
//完成對逆波蘭式的掃描
public static int calculate(List<String> list){
Stack<String> stack = new Stack<String> ();
for (String l : list) {
if(l.matches("\\d+")){
stack.push(l);
}else{
//彈出兩個數
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
int res = 0;
switch (l){
case"+":
res = num1+num2;
break;
case"-":
res = num2-num1;
break;
case"/":
res =num2/num1;
break;
case"*":
res =num1*num2;
break;
default:
break;
}
stack.push(""+res);
}
}
return Integer.parseInt(stack.pop());
}
}