重拾演算法之劍指Offier——包含min函式的棧
阿新 • • 發佈:2018-12-13
題目描述
定義棧的資料結構,請在該型別中實現一個能夠得到棧最小元素的min函式。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
if (stack2.empty()){
stack2.push(node);
}else {
int top1 = stack1.peek();
if (top1 >= node){
stack2.push(node);
}else {
stack2.push(top1);
}
}
stack1.push(node);
}
public void pop() {
stack2.pop();
stack1.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}