Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- public class SpecialStack {
- Stack stack;
- Stack min;
- public SpecialStack() {
- this.stack = new Stack();
- this.min = new Stack();
- }
- public boolean isEmpty() {
- return stack.isEmpty();
- }
- public void push(int x) {
- if (stack.isEmpty()) {
- stack.push(x);
- min.push(x);
- } else {
- /* Just add it to the actual stack */
- stack.push(x);
- /* Get current minimum (only element in min stack)*/
- int current = (int) min.pop();
- if (current < x) {
- min.push(current);
- } else {
- min.push(x);
- }
- }
- }
- public int pop() {
- return (int) stack.pop();
- }
- public int peek() {
- return (int) stack.peek();
- }
- public int getMin() {
- return (int) min.peek();
- }
- @Override
- public String toString() {
- return "SpecialStack{" +
- "stack=" + stack +
- '}';
- }
- public static void main(String[] args) {
- SpecialStack stack = new SpecialStack();
- for (int i = 0; i < 10; i += 2) {
- stack.push(i);
- }
- System.out.println(stack.toString());
- System.out.println(stack.isEmpty());
- System.out.println(stack.peek());
- System.out.println(stack.getMin());
- stack.push(-2);
- System.out.println(stack.toString());
- System.out.println(stack.getMin());
- }
- }
Add Comment
Please, Sign In to add comment