Min Stack

Implement a stack with min() function, which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

 Notice

min operation will never be called if there is no number in the stack.

分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class MinStack {
    private Stack<Integer> stack = new Stack<Integer>();
    private Stack<Integer> stack_min = new Stack<Integer>();
     
    public MinStack() {
        // do initialize if necessary
    }
     
    public void push(int number) {
        // write your code here
        stack.push(number);
        if(!stack_min.empty() && stack_min.peek() < number){
            stack_min.push(stack_min.peek());
        }
        else{
            stack_min.push(number);
        }
    }
 
    public int pop() {
        // write your code here
        int top = -1;
        if(!stack.empty()){
            top = stack.peek();
            stack.pop();
            stack_min.pop();
        }
        return top;
    }
 
    public int min() {
        // write your code here
        return stack_min.empty() ? -1 : stack_min.peek();
    }
}




原文地址:https://www.cnblogs.com/zhxshseu/p/de52b1cfc3c013858c635bafd7423fd1.html