栈的一个小应用——Dijkstra的双栈算术表达式

来源:互联网 发布:js 时分秒 时间选择器 编辑:程序博客网 时间:2024/05/16 23:44
public static Double evl(String str){        Stack<Double> vals = new Stack<Double>();        Stack<Character> op = new Stack<Character>();        char[] ch = str.toCharArray();        for(int i = 0;i < ch.length;i++){            if(ch[i] == '+') op.push(ch[i]);            else if(ch[i] == '-') op.push(ch[i]);            else if(ch[i] == '*') op.push(ch[i]);            else if(ch[i] == '/') op.push(ch[i]);            else if(ch[i] == '(');            else if(ch[i] == ')'){                char o = op.pop();                Double val = vals.pop();                if(o == '+') val = val + vals.pop();                else if(o == '-') val = vals.pop() - val;                else if(o == '*') val = vals.pop() * val;                else if(o == '/') val = vals.pop() / val;                vals.push(val);            }else{                vals.push(Double.parseDouble(Character.toString(ch[i])));            }        }        return vals.pop();    }

当然,这个算法的局限性太大了,但作为栈的一个小应用足够了,
思路:表达式是由数字,操作符,括号组成的,从左到右扫描,
(1)数字就放入操作数栈
(2)操作符就放入符号栈
(3)忽略左括号,遇到右括号,拿出所需要操作符和操作数进行计算,在把结果压入操作数栈。
应用的原理,就是用计算的结果来代替原有的表达式,反复应用这个规律进行计算。而右括号就是开始进行计算的标志。

0 0
原创粉丝点击