码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Min Stack

时间:2016-03-31 09:29:58      阅读:175      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!