题目:
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
提示:
此题要求用“栈”实现“队列”,如果单独用一个栈的话,是不可能的。这里的方法是设置两个栈,具体的思路可以看下面代码的注释。
代码:
class Queue {
private:
// 设置两个栈
stack<int> in, out;
public:
/** Push element x to the back of queue.
* 每次push都push到in这个栈当中
*/
void push(int x) {
in.push(x);
} /** Removes the element from in front of queue.
* 经过peek操作后,可以保证out的顶部存放的是队列的队首。
*/
void pop(void) {
peek();
out.pop();
} /** Get the front element.
* 先检查一下out是否为空,是的话就把in里面的数据“倒进”out,
* 这样一来,out的顶部存放的其实是In的底部的数据,也就是最早push进来的数据。
*/
int peek(void) {
if (out.empty()) {
while(in.size()) {
out.push(in.top());
in.pop();
}
}
return out.top();
} /** Return whether the queue is empty.
* in和out都空了才算是没有数据了
*/
bool empty(void) {
return in.empty() && out.empty();
}
};