LeetCode第155题:
解析:当push(x),x <= min 时先将min进栈,再将x进栈;这也就是说在栈中的每一个min下面都存有前一个min(就是比当前min小的那个)
代码如下:
class MinStack {
/** initialize your data structure here. */
Stack<Integer> stack;
int min;
public MinStack() {
stack = new Stack<>();
min = Integer.MAX_VALUE;
}
public void push(int x) {//关键在于入栈,入栈前将当前最小元素的下一个最小元素连续入栈两次,比最小值大的,也入栈,不过此时的min变量还是最小值,并没有改变
if(x <= min){
stack.push(min);
min = x;
}
stack.push(x);
}
public void pop() {//出栈时,将最小元素检索,此时最小元素的下一个元素也是最小值,将其赋值给min,这是入栈时的特性所决定的。
if(stack.pop() == min){
min = stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
详细的过程分析可参见:
LeetCode第225题:
解析:由于栈和队列的数据结构不同,因此需要使用双队列来完成这个操作。
代码如下:
class MyStack {
private Queue<Integer> a;//输入队列
private Queue<Integer> b;//输出队列
//新建一个队列
//Queue<String> queue = new LinkedList<String>();
/** Initialize your data structure here. */
public MyStack() {
a = new LinkedList<>();
b = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
a.offer(x);
while(! b.isEmpty())
a.offer(b.poll());//将b队列中的元素传给a队列
Queue temp = a;//交换a,b队列中的元素,使得a队列没有在push()的时候始终为空队列
a = b;
b = temp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return b.poll();
}
/** Get the top element. */
public int top() {
return b.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return b.isEmpty();
}
}
栈和队列的数据进出的关系详细可以参见:
因篇幅问题不能全部显示,请点此查看更多更全内容