首页 > 其他 > 详细

包含min函数的栈

时间:2019-04-06 17:23:41      阅读:130      评论:0      收藏:0      [点我收藏+]

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的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();
    }
}

 

包含min函数的栈

原文:https://www.cnblogs.com/fzuhyj/p/10662052.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!