gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
Design a stack that supports push, pop in constant time. Implement the MinStack class:…
- User
Design a stack that supports push, pop in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push (int val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. Use Java
- Assistant
import java.util.Stack;
class MinStack { Stack stack; Stack minStack;
public MinStack() { stack = new Stack<Integer>(); minStack = new Stack<Integer>(); } public void push(int val) { stack.push(val); if(minStack.isEmpty() || val <= minStack.peek()) { minStack.push(val); } } public void pop() { if(stack.isEmpty()) { return; } int val = stack.pop(); if(val == minStack.peek()) { minStack.pop(); } } public int getMin() { return minStack.peek(); }}