创建一个增加返回最小值功能的栈

创建一个栈,增加返回最小值的功能

需求:

改造一个栈,在满足基本的条件下,再添加一个返回最小值的方法

思路:

建立两个栈,一个栈作为普通的数据(StackData)栈,另一个用来记录最小值(StackMin),当添加数据的时候,data栈直接增加数据,而StackMin栈则取出当前最小值与添加值相比较,如果添加值较小,则StackMin栈添加新值,否则再添加最小值.

图示:

代码:

public class SpecialStack {

   
    public static class StackArray{
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public StackArray() {
            this.stackData = new Stack<Integer>();
            this.stackMin  = new Stack<Integer>();
        }

        public void push(int newNum) {
            if (this.stackMin.isEmpty()){
                this.stackMin.push(newNum);
            }else{
                this.stackMin.push(newNum < this.stackMin.peek()?newNum:this.stackMin.peek());
            }
            this.stackData.push(newNum);

        }

        public int pop() {
            this.stackMin.pop();
            return this.stackData.pop();
        }
        public int getMin(){
            if (this.stackMin.isEmpty()){
                throw new RuntimeException("Your Stack is Empty !");
            }
            return this.stackMin.peek();
        }
    }
    public static void main(String[] args) {
        StackArray stack = new StackArray();
        stack.push(3);
        System.out.println(stack.getMin());
        stack.push(5);
        System.out.println(stack.getMin());
        stack.push(2);
        System.out.println(stack.getMin());
        stack.push(4);
        System.out.println(stack.getMin());
        stack.push(1);
        System.out.println(stack.getMin());

    }
}
原文地址:https://www.cnblogs.com/Courage129/p/14165316.html