实现一个栈,除了push和pop操作,还要实现min函数以返回栈中的最小值,

来源:互联网 发布:淘宝上的星巴克月饼券 编辑:程序博客网 时间:2024/06/07 05:14

实现一个栈,除了push和pop操作,还要实现min函数以返回栈中的最小值。
push,pop和min函数的时间复杂度都为O(1)。

import java.util.Stack;public class MinStack {    public static void main(String[] args) {        MinStack mStack = new MinStack(new Stack<Integer>(), new Stack<Integer>());        mStack.push(3);        mStack.push(4);        mStack.push(5);        mStack.push(1);        mStack.push(2);        mStack.push(1);        for(int i=0;i<5;i++) {            System.out.println(mStack.getMin());            System.out.println(mStack.pop());        }    }    private Stack<Integer> dataStack;    private Stack<Integer> minStack;    public MinStack(Stack<Integer> dataStack,Stack<Integer> minStack) {        this.dataStack = dataStack;        this.minStack = minStack;    }    public void push(int num){        this.dataStack.push(num);        if(minStack.isEmpty()) {            minStack.push(num);        }else if(num<=getMin()){            minStack.push(num);        }    }    public int pop() {        if(dataStack.isEmpty()){            throw new RuntimeException("The stack is empty");        }        int value = dataStack.pop();        if(value == getMin()) {            minStack.pop();        }        return value;    }    public int getMin() {        if(minStack.isEmpty()){            throw new RuntimeException("The stack is empty");        }        int min = minStack.peek();        return min;    }}
0 0
原创粉丝点击