包含min函数的栈

来源:互联网 发布:搭车去柏林 知乎 编辑:程序博客网 时间:2024/06/10 22:27

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。


import java.util.Stack;public class Solution {    Stack<Integer> s1 = new Stack<>();    Stack<Integer> s2 = new Stack<>();    public void push(int node) {        s1.push(node);        if(s2.isEmpty() || s2.peek() > node)            s2.push(node);        else            s2.push(s2.peek());    }    public void pop() {        s1.pop();        s2.pop();    }    public int top() {        return s1.peek();    }    public int min() {        return s2.peek();    }}
0 0