可查询最值的栈 -- 算法小结

来源:互联网 发布:佛山mac专柜 编辑:程序博客网 时间:2024/06/18 16:11

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

import java.util.Stack;public class Solution {    Stack<Integer> sta = new Stack<Integer>();    Stack<Integer> min = new Stack<Integer>();    public void push(int node) {        sta.push(node);        if(min.isEmpty()||min.peek()>=node){            min.push(node);        }    }    public void pop() {        if (sta.isEmpty()) {            throw new RuntimeException("Your stack is empty!");        }        if(min.peek()==sta.peek()){            min.pop();        }        sta.pop();    }    public int top() {        return sta.peek();    }    public int min() {        if (min.isEmpty()) {            throw new RuntimeException("Your stack is empty!");        }        return min.peek();    }}

这里写图片描述

原创粉丝点击