包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

 

首先该类必须能实现栈的正常功能,其次再实现min函数

import java.util.Stack;

public class Solution {
    Stack<Integer> s = new Stack<Integer>();   //实现该类的栈功能
    Stack<Integer> m = new Stack<Integer>();    //栈顶保存最小的数,如果node比栈顶大,复制一个栈顶,否则,加入node ;
    public void push(int node) {
        s.push(node);
        if(m.isEmpty() || m.peek()>=node){
            m.push(node);
        }else {
            m.push(m.peek());
        }
    }
    public void pop() {
        s.pop();
        m.pop();
    }

    public int top() {
        return s.peek();
    }

    public int min() {
        return m.peek();
    }
}

 

posted @ 2019-04-06 16:14  萌新上路  阅读(69)  评论(0编辑  收藏  举报