双栈算术表达式求值算法

问题:java 解析并计算字符串表达式 “(1+2)*(3+8/(2*2))”

分析:

1.运算的优先级规则如何表达

     可以使用括号代替优先级规则表示,优先级高的用括号括起来,优先计算括号内的表达式。

2.计算符号和计算因子的存储和操作

    计算符号和计算因子分别存在两个栈(后进先出)中,忽略左括号,当遇到右括号时,弹出一个计算符号和两个计算因子。同时为了方便写程序表达式整体也加到一组括号中,所以字符串表达式更改为:“((1+2)*(3+(8/(2*2))))”

代码如下:

//1.自定义栈,其中包含入栈和出栈方法
public class Stack<T> {
    private List<T> list = new ArrayList<>();

    public void push(T t){
       list.add(t);
    }
    public T pop(){
        T t = list.isEmpty()?null:list.get(list.size() - 1);
        list.remove(list.size()-1);
        return t;
    }

}

//2.表达式解析和计算

public static void main(String[] args) {
        String str = "((1+2)*(3+(8/(2*2))))".replaceAll(" ","" );
        Stack<String> operationStack = new Stack<String>();
        Stack<Integer> integerStack = new Stack<Integer>();
       char[] chars = str.toCharArray();
       List<String> operations = new ArrayList<>();
       operations.add("+");
       operations.add("-");
       operations.add("/");
       operations.add("*");
       for(char c:chars){
           String sc = c+"";
           if(operations.contains(sc)){
                operationStack.push(sc);
           }else if(")".equals(sc)){
               String oper = operationStack.pop();
               Integer d1 = integerStack.pop();
               Integer d2 = integerStack.pop();
               if("+".equals(oper)) integerStack.push(d1+d2);
               else if("-".equals(oper)) integerStack.push(d2-d1);
               else if("*".equals(oper)) integerStack.push(d1*d2);
               else if("/".equals(oper)) integerStack.push(d2/d1);
           }else if("(".equals(sc)){
               continue;
           }else{
               integerStack.push(Integer.valueOf(sc));
           }
       }
        System.out.println("计算结果:"+integerStack.pop());//计算结果:15
}

以上代码并未考虑实际开发场景,只适用于个位正整数的计算,仅为表达思路而已,不喜勿喷!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值