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

 

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 @   java小铭  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示