The stack containing the min function

Topic describes

Define the data structure of the stack, and implement a min function (O (1) time complexity) in this type that gets the smallest element contained in the stack.

Title link: a stack containing the min function

code

import java.util.Stack;

Define the data structure of the stack. Please implement a min function in this type that can get the smallest element contained in the stack (time complexity should be O (1)). * Title link: * https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&&tqId=11173&rp=1&ru=/ta/coding-interviews&qru =/ta/coding-interviews/question-ranking */
public class Jz20 {

    private Stack<Integer> datas = new Stack<Integer>();
    private Stack<Integer> minDatas = new Stack<Integer>();

    public void push(int node) {
        datas.push(node);
        if (minDatas.isEmpty()) {
            minDatas.push(node);
        } else if(node <= minDatas.peek()) { minDatas.push(node); }}public void pop(a) {
        int popData = datas.pop();
        if(popData == minDatas.peek()) { minDatas.pop(); }}public int top(a) {
        return datas.peek();
    }

    public int min(a) {
        returnminDatas.peek(); }}Copy the code

The seemingly insignificant day after day, one day in the future, suddenly let you see the meaning of persistence.