包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。要求在O(1)的时间内得到最小元

素。

可以用两个栈来实现这个功能,栈s1和s2,s2保留s1当中的最小元素,当s1入栈时,s2要考虑新入栈的元素是

否比之前的最小元素小,如果小则s2入栈新元素,如果大,则s2入栈之前的最小元素。当s1出栈时,s2也一同

出栈。

public class Solution {

     private Stack<Integer> s1=new Stack<Integer>();
    private Stack<Integer> s2=new Stack<Integer>();
    
    public void push(int node) {
        s1.push(node);
        if(s2.size()==0){
            s2.push(node);
        }else{
            int s2top=s2.peek();
            if(s2top>node){
                s2.push(node);
            }else{
                s2.push(s2top);
            }
        }  
    }
    
    public void pop() {
        s1.pop();
        s2.pop();
    }
    
    public int top() {
        return s1.peek();
    }
    
    public int min() {
        return s2.peek();
    }
}
posted @ 2016-02-13 18:34  黄大仙爱编程  阅读(72)  评论(0编辑  收藏  举报