-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminStack21.java
More file actions
50 lines (42 loc) · 1.02 KB
/
minStack21.java
File metadata and controls
50 lines (42 loc) · 1.02 KB
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;
import java.util.*;
/*
*
*/
public class minStack21 {
Stack data = new Stack();
Stack min = new Stack();
public void push(int node) {
data.push(node);
//开始min栈的最小元素就是当前入栈的元素
if (min.isEmpty()) {
min.push(node);
}
//min栈不空的时候,那么就开始比较了。
//原始栈中的每一层都对应着一个最小值
if (node < (int) min.peek()) {
min.push(node);
} else {
min.push(min.peek());
}
}
public void pop() {
data.pop();
min.pop();
}
public int top() {
return (int) data.peek();
}
public int min() {
return (int) min.peek();
}
public static void main(String[] args) {
minStack21 st = new minStack21();
st.push(3);
int min = st.min();
System.out.println(min);
st.push(4);
min = st.min();
System.out.println(min);
}
}