forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack_155.java
More file actions
37 lines (31 loc) · 787 Bytes
/
Copy pathMinStack_155.java
File metadata and controls
37 lines (31 loc) · 787 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
import java.util.Stack;
public class MinStack_155 {
/**
* 使用辅助栈法
*/
private Stack<Integer> stack;
private Stack<Integer> stackMin;
public MinStack_155() {
stack = new Stack<Integer>();
stackMin = new Stack<Integer>();
}
public void push(int x) {
stack.push(x);
if(stackMin.isEmpty() || x <= stackMin.peek()) {
stackMin.push(x);
}
}
public void pop() {
//注意点:两个Integer对象不能直接用==来判断值是否相等
if(stack.peek().equals(stackMin.peek())) {
stackMin.pop();
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return stackMin.peek();
}
}