-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
37 lines (34 loc) · 934 Bytes
/
MinStack.java
File metadata and controls
37 lines (34 loc) · 934 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.*;
public class MinStack{
static Stack<Integer> stack=new Stack<>();
static Stack<Integer> minStack= new Stack<>();
public static void push(int val){
stack.push(val);
if (minStack.isEmpty() || minStack.peek()>=val){
minStack.push(val);
}
}
public static void pop(){
if (stack.peek().equals(minStack.peek())){
minStack.pop();
}
stack.pop();
}
public static int top(){
return stack.peek();
}
public static int getMin(){
return minStack.peek();
}
public static void main(String args[]){
push(10);
push(5);
push(2);
push(20);
System.out.println("Top: " + top());
System.out.println("Min: " + getMin());
pop();
System.out.println("Top after pop: " + top());
System.out.println("Min after pop: " + getMin());
}
}