要求完成一個逆波蘭電腦
1.輸入一個逆波蘭表達式(字尾表達式),使用棧計算其結果
2.支援小括号和多為數整數
思路分析
如
(3+4)*5-6
的逆波蘭表達式為
3 4 + 5 x 6 -
1.将表達式
3 4 + 5 x 6 -
放到ArrayList中(友善周遊)
2.将ArrayList傳遞給一個方法,用于計算
3.拿到ArrayList後,從左至右開始周遊,遇到數字直接壓入棧
4.遇到運算符,彈出棧頂和次頂的元素,進行計算,将得到的結果再次放入棧中
5.一直重複,直到ArrayList周遊完畢,可得到最終結果
代碼實作
public class Polanexpr{
public static void main(String[] args) {
String expr = "3 4 + 5 * 6 - "; //逆波蘭表達式 (3+4)*5-6
List<String> listString = getListString(expr); //将逆波蘭表達式轉換為List
int res = cale(listString);
System.out.println(res);
}
//将逆波蘭表達式轉換為list
public static List<String> getListString(String expr){
//将表達式分割成數組
String[] split = expr.split(" ");
List<String> list = new ArrayList<String>();
for(String ele: split){
list.add(ele);
}
return list;
}
//表達式計算
public static int cale(List<String> ls){
Stack<String> stack = new Stack<String>();
//周遊 ls
for(String item: ls){
//使用正則比對數值
if(item.matches("\\d+")){
//數值直接入棧
stack.push(item);
}else{
//如果是運算符則需在棧中彈出兩個數,進行運算
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
int res = 0;
switch (item){
case "+":
res = num1 + num2;
break;
case "-":
res = num2 - num1;
break;
case "*":
res = num1 * num2;
break;
case "/":
res = num2 / num1;
break;
default:
break;
}
//運算的結果壓入棧中
stack.push(res+"");
}
}
//最後留在棧中的元素即為結果
return Integer.parseInt(stack.pop());
}
}
複制