我正在尝试使用两个堆栈实现一个队列,以便更好地理解这两个数据结构。我有以下内容,主要功能是测试:
#include <iostream>
#include <stack>
using namespace std;
template <class T>
class _Stack : public stack<T> {
public:
T pop(){
T tmp=stack::top();
stack::pop();
return tmp;
}
};
template <class T>
class QueueS {
public:
QueueS(){}
bool isEmpty() const{
return pool.empty();
}
void enqueue(const T& el){
while( !output.empty()) {
input.push(output.pop());
}
input.push(el);
}
T dequeue(){
while(!input.empty()){
output.push(input.pop());
}
return output.pop();
}
T firstElement(){
if(output.empty()) {
return NULL;
}
return output.top();
}
private:
_Stack<T> pool;
_Stack<T> input;
_Stack<T> output;
};
int main(){
QueueS<int> n_QueueS;
//fill the queue of integers 0-9
for(int i=0; i<10;i++)
n_QueueS.enqueue(i);
// add another number to the queue
n_QueueS.enqueue(50);
//retrieve the first element without removing it
cout<<"front of the queue: "<<n_QueueS.firstElement()<<endl;
// removing the first 5 elements from the queue
cout<<"deleting first five elements of the queue: ";
for(int i=0; i<5;i++)
cout<<n_QueueS.dequeue()<<" ";
//removing the remainder of the queue and displaying the result
//should see 5 6 7 8 9 50 - see nothing!
cout<<endl<<"deleting remainder of the queue: ";
while(!n_QueueS.isEmpty())
cout<<n_QueueS.dequeue()<<" ";
if(n_QueueS.isEmpty())
cout<<endl<<"Queue is now empty";
else
cout<<endl<<"Error in emptying the queue";
system("pause");
return 0;
}
因此非常好。但是,当我运行我的测试时,删除前五个元素工作正常,它们显示正常。它显示“删除队列的前五个元素:”行,然后按预期显示0 1 2 3 4。
但是,删除后半部分不会像上一个测试用例那样显示文本“删除队列的剩余部分”之后的值。我假设问题很小,但我无法通过调试找到它。也许我忽略了什么?
非常感谢任何帮助!
答案 0 :(得分:2)
首先,你的空检查应该是这样的:
bool isEmpty() const{
return input.empty() && output.empty();
}
在enqueue中,只需按下输入堆栈:
void enqueue(const T& el){
input.push(el);
}
在enqueue和dequeue中,如果输出为空,则将输入移动到输出:
T dequeue(){
if (output.empty())
while(!input.empty()){
output.push(input.pop());
}
// throw exception of output.empty() ??
return output.pop();
}
T firstElement(){
if (output.empty())
while(!input.empty()){
output.push(input.pop());
}
if(output.empty()) {
return T(0); // throw exception?
}
return output.top();
}