C++实现模板(template)实现队列类 | StriveZs的博客

C++实现模板(template)实现队列类

  queue.h头文件 代码:

#ifndef QUEUE_CLASS
#define QUEUE_CLASS
#include
#include
#include “LinkedList.h”

using namespace std;

template
class Queue
{
private:
LinkedList queueList;
public:
Queue(void);
void QInsert(const T& elt);
T QDelete(void);
T QFront(void);
int QLength(void) const;
int QEmpty(void) const;
void QClear(void);
};
template
Queue::Queue(void)
{}
template
int Queue::QLength(void) const
{
return queueList.ListSize();
}
template
int Queue::QEmpty(void) const
{
return queueList.ListEmpty();
}
template
void Queue::QClear(void)
{
queueList.ClearList();
}
template
void Queue::QInsert(const T& elt)
{
queueList.InsertRear(elt);
}
template
T Queue::QDelete(void)
{
if (queueList.ListEmpty())
{
cerr << “Calling QDelete for an empty queue!” << endl;
exit(1);
}
return queueList.DeleteFront();
}
template
T Queue::QFront(void)
{
if (queueList.ListEmpty())
{
cerr << “Calling QFront for an empty queue!” << endl;
exit(1);
}
queueList.Reset();
return queueList.Data();
}
#endif

使用:

#include “queue.h”
#include

using namespace std;
int main()
{
Queue A;
cout<<“输入6个数值用来创建队列:”;
int a=0;
for(int i=0;i<=5;i++)
{
cin>>a;
A.QInsert(a);
}
cout<<“创建成功!”<<endl;
cout << “显示队列中的所有元素为:” ;
while(!A.QEmpty())
{
cout << A.QFront() << " ";
A.QDelete();
}
cout<<endl;
cout<<“判断队列是否为空:”<<(A.QEmpty()==0?“为空”:“不为空”)<<endl;
cout << endl;
cout<<“开始清空队列!”<<endl;
A.QClear();
cout<<“队列成功清空!”<<endl;
return 0;
}

StriveZs wechat
Hobby lead  creation, technology change world.
  • Post author: StriveZs
  • Post link: 1353.html
  • Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.