Question
Min Stack Java Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto
Min Stack Java
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
Hint: Consider each node in the stack having a minimum value.
Include a lot of code comments in your source code. I don't understand the logic behind push(int x), pop() , top(), and getMin(). I know the hint told us to consider each node in the stack having a minimum value, but I am still confused.?
Source Code
//A class Element that has data and minimum
class Element {
public int data;
public int minimum;
public Element next;
public Element(int value, int minimum) {
this.data = value;
this.minimum = minimum;
}
}
//Our class MinStack
public class MinStack {
//Top element of Stack of Type element
public Element top;
public MinStack() {
}
//Push element at Top of stack and keep minimum in minimum
public void push(int x) {
if (top == null) {
top = new Element(x, x);
} else {
Element e = new Element(x, Math.min(x, top.minimum));
e.next = top;
top = e;
}
}
public void pop() {
if (top == null)
return;
Element temp = top.next;
top.next = null;
top = temp;
}
public int top() {
if (top == null)
return -1;
return top.data;
}
public int getMin() {
if (top == null)
return -1;
return top.minimum;
}
public static void main(String[] args) {
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
System.out.println(minStack.getMin()); // --> Returns -3.
minStack.pop();
System.out.println(minStack.top()); // --> Returns 0.
System.out.println(minStack.getMin()); // --> Returns -2.
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started