牛客网 | 包含min函数的栈

来源:互联网 发布:java单例模式添加数据 编辑:程序博客网 时间:2024/06/05 05:15

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

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


0 0
原创粉丝点击