请用栈实现一个队列,支持如下四种操作:
- push(x) – 将元素x插到队尾;
- pop() – 将队首的元素弹出,并返回该元素;
- peek() – 返回队首元素;
- empty() – 返回队列是否为空;
注意:
- 你只能使用栈的标准操作:push to top,peek/pop from top, size 和 is empty;
- 如果你选择的编程语言没有栈的标准库,你可以使用list或者deque等模拟栈的操作;
- 输入数据保证合法,例如,在队列为空时,不会进行pop或者peek等操作;
数据范围:
每组数据操作命令数量 [0,100]
样例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false。
代码:
class MyQueue {
//使用两个栈stk1和stk2来模拟队列
Stack<Integer>stk1,stk2;
/** Initialize your data structure here. */
//初始化队列
public MyQueue() {
//stk1主要负责入队操作(push)
stk1 = new Stack<>();
//stk2主要用于辅助出队操作(pop和peek)
stk2 = new Stack<>();
}
/** Push element x to the back of queue. */
//入队操作:将元素x添加到队列末尾
public void push(int x) {
//直接压入stk1,模拟队列的入队
stk1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
//出队操作:移除并返回队列首部的元素
public int pop() {
//将stk1的所有元素一次弹出并压入stk2,此时stk2的栈顶元素就是队列的首部元素
while(!stk1.empty())stk2.push(stk1.pop());
//弹出试stk2的栈顶元素
int val = stk2.pop();
//将 stk2 剩余的元素重新放回stk1,恢复stk1的状态
while(!stk2.empty())stk1.push(stk2.pop());
return val;
}
/** Get the front element. */
//获取队列首部的元素
public int peek() {
//将stk1的所有元素依次弹出并压入stk2,此时stk2的栈顶就是队列的首部元素
while (!stk1.empty()) stk2.push(stk1.pop());
//获取stk2的栈顶元素
int val = stk2.peek();
//将stk2剩余的元素重新放回stk1,恢复stk1的状态
while (!stk2.empty()) stk1.push(stk2.pop());
return val;
}
/** Returns whether the queue is empty. */
//判断队列是否为空
public boolean empty() {
return stk1.empty();
}
}