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();
    }
}

猜你喜欢

转载自www.cnblogs.com/chanaichao/p/10158793.html