Write a Java program to Implement Min Stack
The code demonstrates the implementation of a MinStack in Java. Let's understand how it works:
- The code starts with the import statement import java.util.Stack; , which imports the Stack class from the java.util package.
- The MinStackImplementation class is defined, serving as the entry point of the program.
- In the main method, a MinStack object named stack is created.
- Several elements are pushed into the stack using the push method. The values pushed are 54, 72, 89, 23, 60, and 68.
- The getMin method is called to retrieve the minimum element from the stack, and its value is printed using the System.out.println statement.
- The pop method is called to remove the top element from the stack.
- The MinStack class is defined to implement the functionality of the minimum stack.
- It contains two private member variables: stack and minStack, both of type Stack<Integer>. These stacks are used to store the elements of the stack and track the minimum element, respectively.
- The constructor MinStack initializes both stacks.
- The push method takes an integer value as a parameter. It pushes the value onto the stack and checks if the minStack is empty or if the value is less than or equal to the top element of the minStack. If either condition is true, the value is pushed onto the minStack as well.
- The pop method removes the top element from the stack. If the popped element is equal to the top element of the minStack, it is also removed from the minStack.
- The top method returns the top element of the stack without removing it.
- The getMin method returns the top element of the minStack, which represents the minimum element in the stack.
Source Code
import java.util.Stack;
public class MinStackImplementation
{
public static void main(String[] args)
{
MinStack stack = new MinStack();
stack.push(54);
stack.push(72);
stack.push(89);
stack.push(23);
stack.push(60);
stack.push(68);
System.out.println("Minimum Element : " + stack.getMin());
stack.pop();
}
}
class MinStack
{
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack()
{
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int value)
{
stack.push(value);
if (minStack.isEmpty() || value <= minStack.peek())
{
minStack.push(value);
}
}
public void pop()
{
if (stack.isEmpty())
{
return;
}
int popped = stack.pop();
if (popped == minStack.peek())
{
minStack.pop();
}
}
public int top()
{
return stack.peek();
}
public int getMin()
{
return minStack.peek();
}
}
Output
Minimum Element : 23