剑指Offer_20

题目

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的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
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Stack;
public class Solution {
Stack<Integer> dataStack = new Stack<>();
Stack<Integer> minStack = new Stack<>();
public void push(int node) {
dataStack.push(node);
if(minStack.isEmpty()){
minStack.push(node);
}
else{
if(node <= minStack.peek()){
minStack.push(node);
}
}
}
public void pop() {
if(!dataStack.isEmpty()){
if(minStack.peek() == dataStack.pop()){
minStack.pop();
}
}
}
public int top() {
if(!dataStack.isEmpty()){
return dataStack.pop();
}
return -1;
}
public int min() {
if(!minStack.isEmpty()){
return minStack.peek();
}
else{
}
return -1;
}
}