Advertisement
GenuineSounds

Tiny Stack

Dec 24th, 2014
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1.  
  2. class MinStack {
  3.  
  4.     Node stack;
  5.     int size;
  6.  
  7.     public void push(int data) {
  8.         if (size == Integer.MAX_VALUE)
  9.             throw new StackOverflowError();
  10.         Node node = new Node(data);
  11.         int min = Integer.MAX_VALUE;
  12.         if (stack != null && stack.min != null)
  13.             min = stack.min.data;
  14.         if (data <= min)
  15.             node.min = node;
  16.         else
  17.             node.min = stack.min;
  18.         node.next = stack;
  19.         stack = node;
  20.         size++;
  21.     }
  22.  
  23.     public void pop() {
  24.         if (stack == null)
  25.             throw new EmptyStackException();
  26.         stack = stack.next;
  27.         size--;
  28.     }
  29.  
  30.     public int top() {
  31.         if (stack == null)
  32.             throw new EmptyStackException();
  33.         return stack.data;
  34.     }
  35.  
  36.     public int getMin() {
  37.         if (stack == null)
  38.             throw new EmptyStackException();
  39.         if (stack.min == null)
  40.             return 0;
  41.         return stack.min.data;
  42.     }
  43.  
  44.     class Node {
  45.  
  46.         int data;
  47.         Node next;
  48.         Node min;
  49.  
  50.         public Node(int data) {
  51.             this.data = data;
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement