155. Minimal stack — stack (Java)

Hits: 0

Design a stack that supports push, pop, top operations, and can retrieve the smallest element in constant time.

push(x) – push element x onto the stack.
pop() – removes the top element from the stack.
top() – Get the top element of the stack.
getMin() – Retrieves the smallest element in the stack.

import java.util.Stack;

public class LeetCode155 {

    static  class  MinStack { 
        //Store all data 
        Stack<Integer> stack = new Stack<>();
         //Used to store the smallest data 
        Stack<Integer> minStack = new Stack<>();

        public  void  push ( int val) {
             //The data is normally pushed to the 
            stack stack .push(val);
             //If minStack is not empty, compare the data val to be pushed to the stack and the data num in minStack, if val If it is small, push it into the stack. If minStack is empty, just push it directly into the stack 
            if (!minStack.isEmpty()){
                 int num = minStack.peek();
                 if (val <= num){
            }else {

        public  void  pop () {
           //When popping the stack, if the number popped from the stack has both stacks, you need to pop them all out of the stack 
          int a =   stack .peek();

          int b = minStack.peek();

          if (a == b){

        public  int  top () {
             //The top element of the stack, just take it directly from the stack 
            return  stack .peek();

        public  int  getMin () {
             //The minimum element is taken directly from minStack 
            return minStack.peek();

    public  static  void  main (String[] args)  {
         //Test code 
        MinStack minStack = new MinStack();

        myStack.push( -2 );

        myStack.push( 0 );

        myStack.push( -3 );





Leave a Reply

Your email address will not be published.