對逆波蘭表達式進行計算

直接上代碼

package learn;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class BoLan {
    public static List<String> getList(String ex){
        List<String> list = new ArrayList<>();
        String[] strings= ex.split(" ");
        for(String s:strings){
            list.add(s);
        }
        return list;
    }
    public static  int cal(List<String> strings) {
        Stack<String> stack = new Stack<>();
        for (String s : strings) {
            if (s.matches("\\d+")) {
                stack.push(s);
            } else {
            int num2=Integer.parseInt(stack.pop());
            int num1=Integer.valueOf(stack.pop());
            int res=0;
            if(s.equals("+")){
                res=num1+num2;
            }else if(s.equals("-")){
                res=num1-num2;
            }else if(s.equals("*")){
                res=num1*num2;
            }else{
                res=num1/num2;
            }
                stack.push(res+"");
            }
        }
        return  Integer.valueOf(stack.pop());
    }
    public static void main(String[] args) {
        String ex="3 4 + 5 * 6 -";
        List<String> list = getList(ex);
        System.out.println(cal(list));

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章