Advertisement
korobushk

min stack

May 7th, 2021
783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. class MinStack {
  2.     Stack<Integer> stack = new Stack();
  3.     Stack<Integer> min = new Stack();
  4.    
  5.     public MinStack() {
  6.  
  7.  
  8.     }
  9.    
  10.     public void push(int val) {
  11.         stack.push(val);
  12.      
  13.         if(min.isEmpty() || min.peek()>=val){
  14.           min.push(val);
  15.          
  16.         }
  17.        
  18.     }
  19.    
  20.     public void pop() {
  21.         if(stack.peek().equals(min.peek())){
  22.             min.pop();
  23.         }
  24.        stack.pop();
  25.        
  26.     }
  27.    
  28.     public int top() {
  29.        
  30.          return stack.peek();
  31.     }
  32.    
  33.     public int getMin() {
  34.         return min.peek();
  35.     }
  36. }
  37.  
  38. /**
  39.  * Your MinStack object will be instantiated and called as such:
  40.  * MinStack obj = new MinStack();
  41.  * obj.push(val);
  42.  * obj.pop();
  43.  * int param_3 = obj.top();
  44.  * int param_4 = obj.getMin();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement