注:此博客不再更新,所有最新文章將發表在個人獨立博客limengting.site。分享技術,記錄生活,歡迎大家關注
題目描述
定義棧的數據結構,請在該類型中實現一個能夠得到棧最小元素的min函數。
import java.util.Stack;
public class Solution {
Stack<Integer> data = new Stack<>();
Stack<Integer> min = new Stack<>();
public void push(int node) {
data.push(node);
if (min.empty()) {
min.push(node);
} else {
int minToPush = node <= min.peek() ? node : min.peek();
min.push(minToPush);
}
}
public void pop() {
data.pop();
min.pop();
}
public int top() {
return data.peek();
}
public int min() {
return min.peek();
}
}