【剑指Offer】面试题30:包含min函数的栈

题目:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

实现

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
import java.util.Stack;

public class Solution {
private Stack<Integer> s = new Stack<>();
private Stack<Integer> min = new Stack<>();

public void push(int node) {
if (min.empty()) {
s.push(node);
min.push(node);
return;
}

s.push(node);
min.push((node < min.peek()) ? node : min.peek());
}

public void pop() {
s.pop();
min.pop();
}

public int top() {
return s.peek();
}

public int min() {
return min.peek();
}
}