请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

答案:
class MyQueue {
private Stack<Integer> one;
private Stack<Integer> two;
public MyQueue() {
one = new Stack<Integer>();
two = new Stack<Integer>();
}
public void push(int x) {
one.push(x);
}
public int pop() {
// 注意是if而不是while
if(two.isEmpty()) {
while(!one.isEmpty()) {
two.push(one.pop());
}
}
return two.pop();
}
public int peek() {
if(two.isEmpty()) {
while(!one.isEmpty()) {
two.push(one.pop());
}
}
//注意:出栈是pop,栈顶是peek
return two.peek();
}
public boolean empty() {
return one.isEmpty() && two.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();
*/
这篇博客介绍了一种使用两个栈来实现先入先出(FIFO)队列的方法。通过在栈one中进行push操作,在栈two中进行pop和peek操作,可以保证队列的正常功能。当需要从队列头部移除元素时,如果栈two为空,则将栈one中的所有元素转移到栈two中,然后从栈two顶部弹出元素。在检查队列是否为空时,判断两个栈都为空即可。这种方法巧妙地利用了栈的特性来实现队列的操作。

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



