Niu Ke (20) stack containing min function

    // 
//     Title description
 //     Define the data structure of the stack, please implement a min function in this type that can get the smallest element of the stack. 
    Stack<Integer> stack = new Stack<Integer> ();
    Stack<Integer> stackMin = new Stack<Integer>();

    public void push(int node) {
        stack.push(node);
        if (stackMin.isEmpty()){
            stackMin.push (node);
        }else {
            if (node<stackMin.peek()){
                stackMin.push (node);
            }
        }
    }

    public void pop() {
        if(stack.pop()==stackMin.peek()){
         stackMin.pop();
        }
    }

    public int top() {
        return stack.peek();
    }

    public  int min () {
         return stackMin.peek ();
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325847137&siteId=291194637