新手练手感--part1.1 栈与队列之设计带有getMin功能的栈

题目:

  实现一个特殊的栈,可以在实现栈的基础功能上,增加获取最小元素的操作

要求:

  pop,push,getMin操作的时间复杂度为O(1)

分析:

  1. 基本功能用栈自己的即可:新建一个栈
  2. getMin:再建一个栈,栈顶到栈底:存的是执行每一步push时候的最小值

想要效果:

stackData 插入 stackMin
2   2
3   2
1   1
4   1

写代码:

public class TestCode {
    //存放栈数据
    private Stack<Integer> stackData = new Stack<Integer>();
    //存放执行每一步之后的最小值
    private Stack<Integer> stackMin = new Stack<Integer>();

    //push
    public void push(Integer pushNum) {
        pushNum = pushNum == null ? 0 : pushNum;
        if(stackMin.isEmpty() || pushNum < stackMin.peek()) {
            stackMin.push(pushNum);
        } else {
            stackMin.push(stackMin.peek());
        }

        stackData.push(pushNum);
    }

    //pop
    public Integer pop() {
        if(stackData.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        stackMin.pop();
        return stackData.pop();

    }
    //getMin
    public Integer getMin() {
        if(stackMin.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }

        return stackMin.peek();
    }

    public static void main(String[] args) {
        TestCode testCode = new TestCode();
        for(int i = 0; i <= 6; i++) {
            if(i % 3 == 2) {
                testCode.pop();
            } else {
                testCode.push((int)(Math.random() * 10) );
            }

            System.out.print("stack of elements: ");
            for(int j = 0; j < testCode.stackData.size(); j++) {
                System.out.print(" " + testCode.stackData.get(j));
            }
            System.out.println("  getMin() = " + testCode.getMin());

        }
    }

}

 

posted @ 2017-06-06 22:51  jiguojing  阅读(295)  评论(0)    收藏  举报