设计一个有getMin功能的栈 pop、push、getMin操作的时间复杂度都是O(1)

class MYStack {
        private Stack stackData;
        private Stack minStack;
        public MYStack() {
            this.stackData = new Stack();
            this.minStack = new Stack();
        }
        
        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;
            }
        }
    }

你可能感兴趣的:(设计一个有getMin功能的栈 pop、push、getMin操作的时间复杂度都是O(1))