-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
42 lines (36 loc) · 802 Bytes
/
MinStack.java
File metadata and controls
42 lines (36 loc) · 802 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
package times_1.minstack;
import java.util.Stack;
/**
* @author zhaohongxin
*/
class MinStack {
Stack<Integer> mainStack;
Stack<Integer> minStack;
public MinStack() {
mainStack = new Stack<>();
minStack = new Stack<>();
}
public void push(int x) {
mainStack.push(x);
if (!minStack.isEmpty()) {
Integer peek = minStack.peek();
if (peek < x) {
minStack.push(peek);
} else {
minStack.push(x);
}
} else {
minStack.push(x);
}
}
public void pop() {
mainStack.pop();
minStack.pop();
}
public int top() {
return mainStack.peek();
}
public int getMin() {
return minStack.peek();
}
}