【发布时间】:2021-10-06 10:50:21
【问题描述】:
我试图使用两个堆栈来实现类队列,但我发现了一个错误。如果我交换两个堆栈(在弹出和前端操作之后),使用 STL 的 swap() 操作,我得到错误的答案,但是当我使用静态代码交换两个堆栈时,我得到正确的答案。 请让我知道到底发生了什么。
#include <bits/stdc++.h>
using namespace std;
template<typename T>
class Queue{
stack<T> A;//non empty stack
stack<T> B;
public:
void push(T x){//O(1)
A.push(x);
};
void pop(){//O(n)
if(A.empty()) return;
while(A.size()>1){
T element=A.top();
A.pop();
B.push(element);
}
//1 element remaining in A
A.pop();
//swap(A,B);//so that A is the non empty stack
//using swap() in this case was giving wrong answer
while(!B.empty()){
T element=B.top();
B.pop();
A.push(element);
}
};
int front(){//O(n)
while(A.size()>1){
T element=A.top();
A.pop();
B.push(element);
}
T element = A.top();
A.pop();
B.push(element);
while(!B.empty()){
T element = B.top();
B.pop();
A.push(element);
}
return element;
};
int size(){
return A.size()+B.size();
};
bool empty(){
return size()==0;
};
};
int main() {
Queue<int> q;
q.push(2);
q.push(3);
q.push(4);
q.pop();
q.push(15);
while(!q.empty())
{
cout<<q.front()<<" ";
q.pop();
}
return 0;
}
还有一件事,在此之前我使用两个队列实现了 Stack,并且 swap() 给出了正确的答案。
【问题讨论】: