思路:
用两个队列互相导来实现一个栈。
c++ code:
class Stack {
private:
int cur = 0;
queue<int> q[2];
public:
// Push element x onto stack.
void push(int x) {
q[cur].push(x);
}
// Removes the element on top of the stack.
void pop() {
while(q[cur].size() > 1) {
q[1 - cur].push(q[cur].front());
q[cur].pop();
}
q[cur].pop();
cur = 1 - cur;
}
// Get the top element.
int top() {
while(q[cur].size() > 1) {
q[1 - cur].push(q[cur].front());
q[cur].pop();
}
int v = q[cur].front();
q[1-cur].push(q[cur].front());
q[cur].pop();
cur = 1 - cur;
return v;
}
// Return whether the stack is empty.
bool empty() {
return q[cur].empty();
}
};
本文介绍了一种使用两个队列互相导数据的方法来实现栈的数据结构。通过不断将当前队列中的元素移动到另一个队列中,可以有效地模拟栈的先进后出特性。
1324

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



