设计一个有getMin功能的栈 pop、push、getMin操

2016-09-23  本文已影响57人  敲一手烂代码
class MYStack {
        private Stack<Integer> stackData;
        private Stack<Integer> minStack;
        public MYStack() {
            this.stackData = new Stack<Integer>();
            this.minStack = new Stack<Integer>();
        }
        
        public int getMin() {
            if (this.minStack.isEmpty()) {
                throw new RuntimeException("栈为空");
            } else {
                return this.minStack.peek();
            }
        }
        
        public void push(int num) {
            this.stackData.push(num);
            if (this.minStack.isEmpty()) {
                this.minStack.push(num);
            } else if (num <= this.minStack.peek()) {
                this.minStack.push(num);
            }
        }
        
        public int pop() {
            if (stackData.isEmpty()) {
                throw new RuntimeException("栈为空");
            } else {
                int val = stackData.pop();
                if (val == minStack.peek()) {
                    minStack.pop();
                }
                return val;
            }
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读