首页 > 其他 > 详细

lintcode-medium-Min Stack

时间:2016-03-31 09:28:26      阅读:216      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

lintcode-medium-Min Stack

原文:http://www.cnblogs.com/goblinengineer/p/5339832.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!