Normally we can use the class template we wrote ourselves to implement the chain queue:
/**********************************链队列的实现********************************/
template<class QElemType>
class LinkQueue;
template<class QElemType>
class QNode {
protected:
QElemType data;
QNode<QElemType> *next;
public:
friend class LinkQueue<QElemType>;
};
template<class QElemType>
class LinkQueue {
protected:
QNode<QElemType> *front;
QNode<QElemType> *rear;
public:
LinkQueue();
virtual ~LinkQueue();
Status EnQueue(QElemType e);
Status DeQueue(QElemType &e);
void PrintQueue();
int QueueLength();
Status QueueEmpty();
};
template<class QElemType>
LinkQueue<QElemType>::LinkQueue()
{
front = rear = new(nothrow)QNode<QElemType>;
if (!front)
exit(LOVERFLOW);
front->next = nullptr;
}
template<class QElemType>
LinkQueue<QElemType>::~LinkQueue()
{
while (front) {
rear = front->next;
delete front;
front = rear;
}
}
template<class QElemType>
Status LinkQueue<QElemType>::EnQueue(QElemType e)
{
QNode<QElemType> *p = new(nothrow)QNode<QElemType>;
if (!p)
return LOVERFLOW;
p->data = e;
p->next = nullptr;
rear->next = p;
rear = p;
return OK;
}
template<class QElemType>
Status LinkQueue<QElemType>::DeQueue(QElemType &e)
{
QNode<QElemType> *p;
if (front == rear)
return ERROR;
p = front->next;
e = p->data;
front->next = p->next;
if (rear == p)
rear = front;
delete p;
return OK;
}
template<class QElemType>
void LinkQueue<QElemType>::PrintQueue()
{
QNode<QElemType> *p = front->next;
while (p) {
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
template<class QElemType>
int LinkQueue<QElemType>::QueueLength()
{
int i = 0;
QNode<QElemType> *p = front->next;
while (p) {
i++;
p = p->next;
}
return i;
}
template<class QElemType>
Status LinkQueue<QElemType>::QueueEmpty()
{
if (front == rear)
return TRUE;
return FALSE;
}
However, the STL queue container that comes with C++ has a great advantage in terms of code size. As long as you add
#include <queue>
You can easily use the following functions:
queue<int> q;
q.empty(); //当队列空时,返回true
q.pop(); //弹出队列第一个元素,注意!并不会返回被弹出元素的值
q.push(x); //将x接到队列的末尾
q.front(); //访问队首元素
q.back(); //访问队尾元素
q.size(); //访问队列中元素个数
Because the queue container does not allow direct operations on q, how should the queue traversal output be performed? I encountered such a problem yesterday when I was completing the data structure hash table. Later, I found that as long as I perform the front operation first, then pop the first element, and at the same time determine whether the queue is empty, I can achieve such a function. . The specific implementation is as follows:
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}