两个队列实现一个栈,核心思想就是压栈的时候,压入空的队列,然后把非空的队列的元素亚到后面去。
queue<int> q1;
queue<int> q2;
void push(int x) {
if(q1.empty()&&q2.empty()){
q1.push(x);
}else if(q2.empty()){
q2.push(x);
while(!q1.empty()){
q2.push(q1.front());
q1.pop();
}
}else{
q1.push(x);
while(!q2.empty()){
q1.push(q2.front());
q2.pop();
}
}
}
// Removes the element on top of the stack.
void pop() {
if(!q1.empty()) q1.pop();
else if(!q2.empty()) q2.pop();
}
// Get the top element.
int top() {
if(!q1.empty()) return q1.front();
else if(!q2.empty()) return q2.front();
else return NULL;
}
// Return whether the stack is empty.
bool empty() {
return q2.empty()&&q1.empty();
}
本文介绍了一种使用两个队列实现栈的方法。核心思想是在压栈时选择空队列进行压入操作,并将非空队列的所有元素转移到另一个队列中。文章详细展示了如何通过这种方式实现栈的基本操作:压栈、弹栈、获取栈顶元素及判断栈是否为空。

699

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



