c++ - 使用两个堆栈实现队列 - 出列测试问题?

标签 c++ stack queue

为了更好地理解这两种数据结构,我正在尝试实现一个具有两个堆栈的队列。我有以下内容,主要功能用作测试:

#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。

但是,删除后半部分不会像前面的测试用例那样显示文本“删除队列的剩余部分”之后的值。我假设问题很小,但我无法通过调试找到它。也许我忽略了什么?

如有任何帮助,我们将不胜感激!

最佳答案

首先,你的空支票应该是这样的:

bool isEmpty() const{
   return input.empty() && output.empty();
}

在入队中,只是压入输入栈:

void enqueue(const T& el){
   input.push(el);    
}

在入队和出队中,如果输出为空,则将输入移动到输出:

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();
}

关于c++ - 使用两个堆栈实现队列 - 出列测试问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17014794/

相关文章:

c++ - 如何查找字符串是否与数组中找到的字符串匹配?

c++ - 重载 operator<< 时出现 "operator<< must take exactly one argument"形式的错误

c++ - 创建具有专业外观(和行为!)的表单设计器

python - 运行 python pyd 模块的几个独立实例

python - Tornado 异步队列不等待

javascript - jQuery:让事件在彼此之后运行(队列)

c# - 服务栈服务器事件

javascript - Array.shift 和 JavaScript 中的链表等效项之间的性能差异是什么

c++ - 将中缀表示法表达式转换为后缀表示法

c - 从队列中删除偶数