问题描述:
Implement the following operations of a stack using queues.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
empty() – Return whether the stack is empty.
Notes:
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
分析:这里可能最讨厌的一点就是pop的过程,那这里需要两个队列来实现,我是使用一个主队列,一个辅助队列,在pop完之后,将辅助队列的值恢复到 主队列中。
有一些人是使用两个队列,两个队列不分主次。使用一个索引来标示到底使用哪个队列。
此外,我把头节点用一个属性值来标示,这样当取top值时,就直接返回这个属性值即可。
代码如下:0ms
class Stack {
queue<int> q;
queue<int> tmp;
int topValue;
public:
// Push element x onto stack.
void push(int x) {
q.push(x);
topValue = x;
}
// Removes the element on top of the stack.
void pop() {
while (q.size() > 1) {
tmp.push(q.front());
q.pop();
}
q.pop();
while (tmp.size() > 0) {
q.push(tmp.front());
tmp.pop();
}
topValue = q.back();
}
// Get the top element.
int top() {
return topValue;
}
// Return whether the stack is empty.
bool empty() {
return q.empty();
}
};