实现一个特殊的栈,返回栈中最小元素

465 阅读1分钟

实现一个特殊的栈,在实现栈的基本功能的基础上,在实现返回栈中最小元素的操作。

  • pop、push、getMin操作的时间复杂度为O(1)。
  • 设计栈的类型可以使用现成的栈结构。
import java.util.Stack;
public class GetMinSrack {
    public static class MyStack{
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;
        public MyStack(){
            this.stackData = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }
        public void push(int newNum){
            if(this.stackMin.isEmpty()){
                this.stackMin.push(newNum);
            }else if(newNum <= this.getMin()){
                this.stackMin.push(newNum);
            }else{
                this.stackMin.push(this.stackMin.peek());
            }
            this.stackData.push(newNum);
        }
        public int pop(){
            if(this.stackData.isEmpty()){
                throw new RuntimeException("stack is empty");
            }
            this.stackMin.pop();
            return stackData.pop();
        }
        public int getMin(){
            if(this.stackMin.isEmpty()){
                throw new RuntimeException("stack is empty");
            }
            return this.stackMin.peek();
        }
    }

}