题目网址:https://leetcode-cn.com/problems/implement-queue-using-stacks/
这题的思路与”用队列实现栈“是类似的。
这里我们需要两个栈来辅助我们实现队列,两个栈分别是A和B
A栈:负责入队列操操作,B栈负责出队列操作
入队列操作:需要先判断一下B是不是空栈,如果是空栈,就直接push,如果不是空,就需要将B的元素push到A中,保持原有队列的顺序。
出队列操作:需要判断一下A栈是不是空栈,如果A栈不是空,就需要将A的元素都push到B中,这样A栈底的元素就跑到B栈顶去了,只要对B进行出栈就实现了出队列的操作。如果A是空,直接对B操作
取栈顶元素操作:如上,唯一的不同是,B栈顶的元素无需出栈

这题的关键是无论怎么是哪个操作,必有一个栈是空的。
class MyQueue {
/** Initialize your data structure here. */
public MyQueue() {
}
Stack<Integer> A = new Stack<>();
Stack<Integer> B = new Stack<>();
/** Push element x to the back of queue. */
public void push(int x) {
if(!B.isEmpty()){
int ret = B.pop();
A.push(ret);
}
A.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(A.isEmpty()&&B.isEmpty()){
return 0;
}
while (!A.isEmpty()){
int ret = A.pop();
B.push(ret);
}
int result = B.pop();
return result;
}
/** Get the front element. */
public int peek() {
if(A.isEmpty()&&B.isEmpty()){
return 0;
}
while (!A.isEmpty()){
int ret = A.pop();
B.push(ret);
}
return B.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return A.isEmpty() && B.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/

本篇博客探讨如何利用两个栈A和B来实现队列的功能。入队操作时,若B栈非空,则将B栈元素转移至A栈;出队操作时,若A栈非空,则将A栈元素转移至B栈并出队。关键在于始终保持一个栈为空,以保持队列的正确顺序。
831

被折叠的 条评论
为什么被折叠?



