-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
51 lines (39 loc) · 1021 Bytes
/
MinStack.java
File metadata and controls
51 lines (39 loc) · 1021 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Stack;
public class MinStack {
public static void main(String[] args) {
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
System.out.println(minStack.getMin()); // return -3
minStack.pop();
System.out.println(minStack.top()); // return 0
System.out.println(minStack.getMin()); // return -2
}
Stack<Integer> st = new Stack<>();
Stack<Integer> min = new Stack<>();
public MinStack() {
}
public void push(int val) {
if (st.size() == 0) {
st.push(val);
min.push(val);
} else {
st.push(val);
if (min.peek() < val)
min.push(min.peek());
else
min.push(val);
}
}
public void pop() {
st.pop();
min.pop();
}
public int top() {
return st.peek();
}
public int getMin() {
return min.peek();
}
}