题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
解题
import java.util.Stack;
public class Solution {
//存放数据
Stack<Integer> stackA = new Stack<Integer>();
//存放小的元素
Stack<Integer> stackB = new Stack<Integer>();
public void push(int node) {
stackA.push(node);
if(stackB.isEmpty() || node <= stackB.peek())
stackB.push(node);
}
public void pop() {
if(stackA.pop().equals(stackB.peek()))
stackB.pop();
}
public int top() {
return stackA.peek();
}
public int min() {
return stackB.peek();
}
}