lintcode-medium-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.

Example
push(1)
pop()   // return 1
push(2)
push(3)
min()   // return 2
push(1)
min()   // return 1

public class MinStack {
    
    class node{
        int val;
        int min;
        node next;
        
        public node(int val){
            this.val = val;
            this.min = Integer.MAX_VALUE;
            this.next = null;
        }
    }
    
    private node top;
    
    public MinStack() {
        // do initialize if necessary
    }

    public void push(int number) {
        // write your code here
        if(this.top == null){
            this.top = new node(number);
            this.top.min = number;
        }
        else{
            node temp = new node(number);
            temp.min = Math.min(number, this.top.min);
            temp.next = this.top;
            this.top = temp;
        }
        
        return;
    }

    public int pop() {
        // write your code here
        int result = this.top.val;
        this.top = top.next;
        
        return result;
    }

    public int min() {
        // write your code here
        
        return this.top.min;
    }
}

 

posted @ 2016-03-31 08:51  哥布林工程师  阅读(121)  评论(0编辑  收藏  举报