-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
36 lines (30 loc) · 834 Bytes
/
MinStack.java
File metadata and controls
36 lines (30 loc) · 834 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
import java.util.*;
// Given a stack class. Design a stack with getMin() function.
class MinStack {
private Stack<Integer> mainSt;
private Stack<Integer> minSt;
public MinStack() {
mainSt = new Stack<>();
minSt = new Stack<>();
}
public void push(int x) {
mainSt.push(x);
if(minSt.isEmpty() || x <= minSt.peek()) {
minSt.push(x);
}
}
public void pop() {
if(!mainSt.isEmpty()) {
int topEl = mainSt.pop();
if(!minSt.isEmpty() && minSt.peek() == topEl) {
minSt.pop();
}
}
}
public int top() {
return mainSt.isEmpty() ? -1 : mainSt.peek();
}
public int getMin() {
return minSt.isEmpty() ? -1 : minSt.peek();
}
}