-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
49 lines (48 loc) · 1.14 KB
/
MinStack.java
File metadata and controls
49 lines (48 loc) · 1.14 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
package fastds;
import java.util.*;
public class MinStack {
Stack<Integer> minStack,stack;
public MinStack(){
minStack=new Stack<>();
stack=new Stack<>();
}
public void push(int x){
if(minStack.isEmpty() && stack.isEmpty()){
minStack.push(x);
stack.push(x);
}else{
if(x < minStack.peek()){
minStack.push(x);
}
stack.push(x);
}
}
public int pop(){
if(minStack.peek().equals(stack.peek())){
minStack.pop();
}
return stack.pop();
}
public int getMin(){
return minStack.peek();
}
public void display(){
stack.stream().forEach((x) -> {
System.out.println(" "+x);
});
}
public static void main(String[] args) {
MinStack m=new MinStack();
m.push(10);
m.push(20);
m.push(30);
m.push(40);
m.push(50);
System.out.println("MIN: "+m.getMin());
m.push(3);
m.push(1);
m.push(9);
System.out.println("MIN: "+m.getMin());
m.pop();
}
}