Advertisement
exmkg

Untitled

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