Topic: Implementing stacks with queues
- Topic description:
Use the queue to implement the following operations on the stack:
push(x) – element x is pushed onto the stack
pop() – remove the top element of the stack
top() – get the top element of the stack
empty() – return whether the stack is empty
Notice:
- You can only use the basic operations of the queue - namely push to back, peek/pop from front, size, and is empty which are legal.
- The language you are using may not support queues. You can use list or deque (double-ended queue) to simulate a queue, as long as it's standard queue operations.
- All operations are assumed to be valid (eg, no pop or top operations are called on an empty stack).
C++:
#include <queue>
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
std::queue<int> temp_queue; //临时队列
temp_queue.push(x); //将新元素push进入临时队列temp_queue
while(!_data.empty())
{
temp_queue.push(_data.front()); //将原队列内容push进入临时队列temp_queue
_data.pop();
}
while(!temp_queue.empty())
{
_data.push(temp_queue.front()); //将临时队列temp_queue元素push进入数据队列data_queue
temp_queue.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() { //pop弹出栈顶并返回栈顶元素
int x = _data.front(); //取栈顶元素,即为队列头部元素
_data.pop(); //弹出队列头部元素
return x; //返回取出的队列头部元素x,即为栈顶元素
}
/** Get the top element. */
int top() {
return _data.front(); //返回栈顶即直接返回队列头部元素
}
/** Returns whether the stack is empty. */
bool empty() {
return _data.empty(); //
}
private:
std::queue<int> _data; //_data数据队列存储元素的顺序就是栈存储元素的顺序
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* bool param_4 = obj.empty();
*/