-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMinStack.java
50 lines (44 loc) · 1.07 KB
/
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
package offer.problem30;
import java.util.Objects;
import java.util.Stack;
/**
* Created with IntelliJ IDEA
*
* @Author yuanhaoyue swithaoy@gmail.com
* @Description 30.包含min函数的栈
* @Date 2019-01-24
* @Time 1:31
*/
public class MinStack {
private Stack<Integer> stack = new Stack<>();
//辅助栈,存放最小值
private Stack<Integer> minStack = new Stack<>();
public void push(int node) {
stack.push(node);
if (minStack.empty() || minStack.peek() >= stack.peek()) {
minStack.push(node);
}
}
public Integer min() {
if (minStack.empty()) {
return null;
}
return minStack.peek();
}
public Integer pop() {
if (stack.empty()) {
return null;
}
int num = stack.pop();
if (!minStack.empty() && Objects.equals(num, minStack.peek())) {
minStack.pop();
}
return num;
}
public Integer peek() {
if (stack.empty()) {
return null;
}
return stack.peek();
}
}