数据结构：队列的链式存储结构

```#include <iostream>
#include <stdlib.h>
using namespace std;

/*******************************
*
*    链队列的结构实现
*
*******************************/
typedef int QElemType;
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode, *QNodePtr;

typedef struct
{
QNodePtr front;
QNodePtr rear;

/*******************************
*
*    链队列的操作实现
*
*******************************/

/*初始化一个链队列*/
{
cout << "Init LinkQueue ..." << endl;

QNodePtr p = (QNodePtr)malloc(sizeof(QNode));
p->next = NULL;
lq->front = lq->rear = p;

return true;
}

/*插入元素e为Q的新的队尾元素*/
{
QNodePtr s = (QNodePtr)malloc(sizeof(QNode));
if(!s)
{
exit(0);
}
s->data = e;
s->next = NULL;

lq->rear->next = s;
lq->rear = s;

return true;
}
/*删除队列的队头元素，用e返回其值*/
{
QNodePtr p = NULL;

if(lq->front == lq->rear)
{
return false;
}
p = lq->front->next;

*e = p->data;

lq->front->next = p->next;

if(p == lq->rear)/*若队头同时又是队尾，则删除后将rear指向头结点*/
{
lq->rear = lq->front;
}
cout << "DeQueue Item: " << *e << endl;
free(p);

return true;
}
/*销毁队列，包括头结点*/
{
cout << "Destroy Queue... " << endl;
while(lq->front)
{
lq->rear = lq->front->next;
free(lq->front);
lq->front = lq->rear;
}

return true;
}
/*将队列清空，但是保留头结点*/
{
if(lq->front == lq->rear)
{
return true;
}
cout << "Clear Queue ..." << endl;
QNodePtr p = lq->front->next;
QNodePtr q = NULL;

lq->front->next = NULL;
lq->rear = lq->front;

while(p)
{
q = p->next;
free(p);
p = q;
}

return true;
}
/*判断队列是否为空*/
{
return lq.front == lq.rear;
}

/*返回队列中结点的个数*/
{
int count = 0;
if(lq.front == NULL)//队列没有初始化
{
return 0;
}
QNodePtr p = lq.front->next;
while(p)
{
p = p->next;
count++;
}

return count;
}
/*返回队列的队头元素*/
{
QNodePtr p;
if(lq->front == lq->rear)
{
return false;
}
p = lq->front->next;
*e = p->data;

cout << "Get Top Item: " << *e << endl;

return true;
}

/*遍历队列中的各个元素*/
{
if(lq.front == lq.rear)
{
return false;
}
cout << "Queue Traverse ..." << endl;
QNodePtr p = lq.front->next;

while(p)
{
cout << p->data <<' ';
p = p->next;
}
cout << endl;

return true;
}

void main(void)
{
InitQueue(&lq);
for(int i = 0; i < 5; i++)
{
EnQueue(&lq, i);
}

QueueTraverse(lq);
int result;
GetTop(&lq, &result);
DeQueue(&lq, &result);
if(!IsEmptyQueue(lq))
{
cout << "Queue Length: " << QueueLength(lq) << endl;
}
QueueTraverse(lq);
DestroyQueue(&lq);

system("pause");
}```

原文作者：stemon
原文地址: https://www.cnblogs.com/stemon/p/4284280.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。