数据结构-实现逆波兰计算器

 

package com.stack;

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

public class Poland {
    public static void main(String[] args) {
        String suff= "30 4 + 5 * 6 -";

        List<String> list=getListString(suff);
        System.out.println(list);

        System.out.println(calculate(list));
    }

    public static List<String> getListString(String suff){
            String[] split = suff.split(" ");
            List<String> list=new ArrayList<String>();
            for(String s:split){
                list.add(s);
            }
            return list;
    }

    public  static int calculate(List<String> list){
        Stack<String> stack = new Stack<String>();
        for(String item:list){
            if(item.matches("\\d+")){
                stack.add(item);
            }else{
                int num2=Integer.parseInt(stack.pop());
                int num1=Integer.parseInt(stack.pop());
                int res=0;
                if(item.equals("+")){
                    res = num1 +num2;
                }else if(item.equals("-")){
                    res = num1 - num2;
                }else if(item.equals("*")){
                    res = num1 * num2;
                }else if(item.equals("/")){
                    res = num1/num2;
                }else{
                    throw new RuntimeException("运算符输入错误");
                }
                stack.push(""+res);
            }


        }
        return Integer.parseInt(stack.pop());
    }
}

 

posted @ 2023-02-04 23:10  java小铭  阅读(22)  评论(0)    收藏  举报