Stack

Stack是java提供的一种后进先出的栈,继承于Vector,故为线程安全,且其扩容等操作设计与Vector一样。其中pop()为弹出顶层,push()为压入栈的操作

/**
 * The <code>Stack</code> class represents a last-in-first-out
 * (LIFO) stack of objects. It extends class <tt>Vector</tt> with five
 * operations that allow a vector to be treated as a stack. The usual
 * <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a
 * method to <tt>peek</tt> at the top item on the stack, a method to test
 * for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt>
 * the stack for an item and discover how far it is from the top.
 * <p>
 * When a stack is first created, it contains no items.
 *
 * <p>A more complete and consistent set of LIFO stack operations is
 * provided by the {@link Deque} interface and its implementations, which
 * should be used in preference to this class.  For example:
 * <pre>   {@code
 *   Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
 *

如注释所说,其为后进先出的栈,也能存储null,pop()会弹出顶层等等。

下面是栈Stack实现的类似js的eval()方法,即计算算式的方法(依据算法第四版)

public static void main(String[] args) {

        String str = "(1+((2+3)*(4*5)))";
        Stack<Character> ops = new Stack<>();
        Stack<Double> vals = new Stack<>();
        for(int i = 0;i<str.length();i++){
            char c = str.charAt(i);
            if(c=='(') {
                continue;
            }else if(c=='+'||c=='-'||c=='*'||c=='/'){
                ops.push(c);
            }else if(c==')') {
                double firstVal = vals.pop();
                double secondVal = vals.pop();
                char op = ops.pop();
                double result;
                if(op=='+'){
                    result = secondVal + firstVal;
                } else if (op == '-') {
                    result = secondVal - firstVal;
                }
                else if(op=='*'){
                    result = secondVal * firstVal;
                }
                else {
                    result = secondVal / firstVal;
                }
                vals.push(result);
            } else {
                vals.push(Double.valueOf(String.valueOf(c)));
            }
        }
        System.out.println(vals.pop());


    }

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值