题目:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
思路:构建两个辅助栈,栈1作为数据栈,存储数据;栈2存储当前最小值。push时,保证栈2为最小值。pop时,如果出栈和栈2的栈顶元素相等,栈1栈2都要出栈,保证有效的最小值。
public class Solution {
Stack<Integer> stack1 = new Stack();
Stack<Integer> stack2 = new Stack();
public void push(int node) {
stack1.push(node);
if (stack2.empty()) {
stack2.push(node);//栈2如果为null则直接压入
} else if (node < stack2.peek()) {//否则如果比栈顶元素小才压入
stack2.push(node);
}
}
public void pop() {
if (!stack1.empty()) {
if (stack1.peek() == stack2.peek()) {
//如果当前要出栈的元素为当前最小值,栈2也要出栈
stack2.pop();
}
stack1.pop();
}
}
public int top() {
return stack1.peek();//栈1中的元素为栈顶元素
}
public int min() {
return stack2.peek();
}
}