The sword refers to the stack of Offer-28 that contains the min function

Stack<Integer> A;
Stack<Integer> B;

public MinStack28 () {
    // Use two stacks to achieve A for all data and B for decrement
    A = new Stack<>();
    B = new Stack<>();
}

public void push(int x) {
    A.push(x);
    // When inserting, it is judged that the top of the stack of B is larger than the current inserted data before inserting so that the minimum value can be taken out at all times
    if (B.empty() || B.peek() >= x){
        B.push(x);
    }
}

public void pop() {
    // When A is popped from the stack, it is judged whether it is the same as the top of the B stack, and then B is also popped from the stack
    if (A.pop().equals(B.peek())){
        B.pop();
    }
}

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

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

 

Guess you like

Origin blog.csdn.net/a792396951/article/details/113842244