牛客网-包含min函数的栈

题目描述

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

https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

解题

import java.util.Stack;

public class Solution {

    //存放数据
    Stack<Integer> stackA = new Stack<Integer>();
    //存放小的元素
    Stack<Integer> stackB = new Stack<Integer>();


    public void push(int node) {
        stackA.push(node);
        if(stackB.isEmpty() || node <= stackB.peek())
            stackB.push(node);

    }

    public void pop() {
        if(stackA.pop().equals(stackB.peek()))
            stackB.pop();
    }

    public int top() {
        return stackA.peek();
    }

    public int min() {
        return stackB.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_17623363/article/details/107556927