forked from kbeathanabhotla/DSAAJ2-Answers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chap03.question.25.MinStack.java
51 lines (43 loc) · 1.24 KB
/
Chap03.question.25.MinStack.java
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
50
51
//Chap03.question.25.MinStack.java
import java.util.ArrayList;
import java.util.EmptyStackException;
public class MinStack<T extends Comparable<? super T>> {
private ArrayList<Pair> stack;
public MinStack() {
stack = new ArrayList<>();
}
public void push(T t) {
if (stack.isEmpty()) {
stack.add(new Pair(0, t));
} else {
Pair pair;
int lastMinIndex = stack.get(stack.size() - 1).minIndex;
T lastMin = stack.get(lastMinIndex).value;
if (lastMin.compareTo(t) < 0) {
stack.add(new Pair(lastMinIndex, t));
} else {
stack.add(new Pair(stack.size(), t));
}
}
}
public T pop() {
if (stack.isEmpty())
throw new EmptyStackException();
T t = stack.get(stack.size() - 1).value;
stack.remove(stack.size() - 1);
return t;
}
public T findMin() {
if (stack.isEmpty())
throw new EmptyStackException();
return stack.get(stack.get(stack.size() - 1).minIndex).value;
}
private class Pair {
T value;
int minIndex;
Pair(int i, T t) {
minIndex = i;
value = t;
}
}
}