題目描述
定義棧的資料結構,請在該類型中實作一個能夠得到棧最小元素的min函數。
解題思路
用一個棧stack儲存資料,用另外一個棧temp儲存依次入棧最小的數
比如,stack中依次入棧
5, 3, 4, 10, 2, 12, 1, 8
則temp依次入棧
5, 3, 3,3, 2, 2, 1, 1
每次入棧的時候,如果入棧的元素比min中的棧頂元素小或等于則入棧,否則用最小元素入棧。
參考代碼
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack<>();
Stack<Integer> temp = new Stack<>();
int min = Integer.MAX_VALUE;
public void push(int node) {
stack.push(node);
if(node < min){
temp.push(node);
min = node;
}
else
temp.push(min);
}
public void pop() {
stack.pop();
temp.pop();
}
public int top() {
int t = stack.pop();
stack.push(t);
return t;
}
public int min() {
int m = temp.pop();
temp.push(m);
return m;
}
}