请你仅使用两个栈实现先入先出队列。
队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
解题思路:
栈的特点是“先进后出”,而队列的特点是“先进先出”。因此我们可以利用两个栈实现队列的特性。首先将一个栈当作输入栈,用于存储传入的数据;另一个辅助栈当作输出栈,用于输出操作。
具体实现:
- push: 首先向输入栈压入数据,其次在辅助栈为空的时候将输入栈的元素移到辅助栈
- 每次pop或peek时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序
- empty:当两个栈都没元素时,才表明为空
具体代码:
class MyQueue {
Deque<Integer> stack_1;
Deque<Integer> stack_2;
/** Initialize your data structure here. */
// 构造函数:新建两个栈
public MyQueue() {
stack_1 = new LinkedList<>();
stack_2 = new LinkedList<>();
}
// 首先向栈1压入元素,其次在栈2为空的时候将栈1的元素移到栈2
/** Push element x to the back of queue. */
public void push(int x) {
stack_1.push(x);
if(stack_2.isEmpty()) {
move(stack_1, stack_2);
}
}
// 首先在栈2为空的时候将栈1的元素移到栈2,返回栈2栈顶的元素
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack_2.isEmpty()) {
move(stack_1, stack_2);
}
if(!stack_2.isEmpty()) {
return stack_2.pop();
}
return -1;
}
// 首先在栈2为空的时候将栈1的元素移到栈2,获取栈2栈顶的元素
/** Get the front element. */
public int peek() {
if(stack_2.isEmpty()) {
move(stack_1, stack_2);
}
if(!stack_2.isEmpty()) {
return stack_2.peek();
}
return -1;
}
// 当两个栈都没元素时,才表明为空
/** Returns whether the queue is empty. */
public boolean empty() {
return stack_1.isEmpty() && stack_2.isEmpty();
}
// 将stack_1的元素移动到stack_2中
public void move(Deque<Integer> stack_1, Deque<Integer> stack_2) {
while(!stack_1.isEmpty()) {
stack_2.push(stack_1.pop());
}
}
}
/**
* 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();
*/
本文介绍了如何利用两个栈来模拟队列的操作,包括push、pop、peek和empty。通过将一个栈作为输入栈,另一个栈作为输出栈,实现了队列的先进先出特性。在pop和peek操作时,如果输出栈为空,则将输入栈所有元素移到输出栈,确保队列的正确顺序。这种方法巧妙地利用了栈和队列的特性,实现了高效的队列操作。

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



