20.包含min函数的栈

Posted chanaichao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了20.包含min函数的栈相关的知识,希望对你有一定的参考价值。

题目描述

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

题目解答

import java.util.Stack;

public class Solution {
    private Stack<Integer> stackData=new Stack<>();
    private Stack<Integer> stackMin=new Stack<>();
    
    public void push(int node) {
        if(stackMin.isEmpty()){
            stackMin.push(node);
        }else if(node<min()){
            stackMin.push(node);
        }
        stackData.push(node);
    }
    
    public void pop() {
        if(stackData.isEmpty()){
            throw new RuntimeException("the stack is empty");
        }
        int value=stackData.pop();
        if(value==min()){
            stackMin.pop();
        }
    }
    
    public int top() {
        if(stackData.isEmpty()){
            throw new RuntimeException("the stack is empty");
        }
        return stackData.peek();
    }
    
    public int min() {
        if(stackMin.isEmpty()){
            throw new RuntimeException("the stack is empty");
        }
        return stackMin.peek();
    }
}

 

以上是关于20.包含min函数的栈的主要内容,如果未能解决你的问题,请参考以下文章

剑指offer(20)包含min函数的栈

20.包含min函数的栈

牛客(20)包含min函数的栈

20.包含min函数的栈(python)

剑指Offer20包含min函数的栈

剑指offer-包含min函数的栈20