包含min函数的栈、合并min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
public class Solution {
Stack<Integer> stacks1 = new Stack<>();
Stack<Integer> stacks2 = new Stack<>();
public void push(int node) {
stacks1.push(node);
if(stacks2.size()==0){
stacks2.push(node);
}else{
if(node>stacks2.peek()){
stacks2.push(stacks2.peek());
}else {
stacks2.push(node);
}
}
}
public void pop() {
if(stacks1.size()>0)
stacks1.pop();
if(stacks2.size()>0)
stacks2.pop();
}
public int top() {
if(stacks1.size()>0){
return stacks1.peek();
}
return 0;
}
public int min() {
if(stacks2.size()>0){
return stacks2.peek();
}else {
return 0;
}
}
}