Filip_Markoski

[ADS] SpecialStack

Nov 9th, 2017
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. import java.util.Stack;
  2.  
  3. public class SpecialStack {
  4.  
  5.     Stack stack;
  6.     Stack min;
  7.  
  8.     public SpecialStack() {
  9.         this.stack = new Stack();
  10.         this.min = new Stack();
  11.     }
  12.  
  13.     public boolean isEmpty() {
  14.         return stack.isEmpty();
  15.     }
  16.  
  17.     public void push(int x) {
  18.         if (stack.isEmpty()) {
  19.             stack.push(x);
  20.             min.push(x);
  21.         } else {
  22.             /* Just add it to the actual stack */
  23.             stack.push(x);
  24.             /* Get current minimum (only element in min stack)*/
  25.             int current = (int) min.pop();
  26.             if (current < x) {
  27.                 min.push(current);
  28.             } else {
  29.                 min.push(x);
  30.             }
  31.  
  32.         }
  33.     }
  34.  
  35.     public int pop() {
  36.         return (int) stack.pop();
  37.     }
  38.  
  39.     public int peek() {
  40.         return (int) stack.peek();
  41.     }
  42.  
  43.     public int getMin() {
  44.         return (int) min.peek();
  45.     }
  46.  
  47.     @Override
  48.     public String toString() {
  49.         return "SpecialStack{" +
  50.                 "stack=" + stack +
  51.                 '}';
  52.     }
  53.  
  54.     public static void main(String[] args) {
  55.         SpecialStack stack = new SpecialStack();
  56.  
  57.         for (int i = 0; i < 10; i += 2) {
  58.             stack.push(i);
  59.         }
  60.  
  61.         System.out.println(stack.toString());
  62.  
  63.         System.out.println(stack.isEmpty());
  64.         System.out.println(stack.peek());
  65.         System.out.println(stack.getMin());
  66.         stack.push(-2);
  67.         System.out.println(stack.toString());
  68.         System.out.println(stack.getMin());
  69.  
  70.     }
  71. }
Add Comment
Please, Sign In to add comment