signed

QiShunwang

“诚信为本、客户至上”

Stack

2021/3/21 1:04:02   来源:

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());


    }