声明:本博客参考《大话数据结构》书籍。
1、引入两个指针front和rear,其中front指向头结点,rear指向队尾结点,如下图所示
2、当队列为空时,front和rear都指向头结点,
3、出队操作时需注意,若链表除头结点外只剩下一个元素时,则需将rear指向头结点,
4、具体代码实现如下:
#include<iostream>
using namespace std;
typedef int QElemType;
typedef int Status;
#define MAXSIZE 10
#define true 1
#define false 0
typedef int QElemType;
typedef struct QNode //结点结构
{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front, rear;//队头、队尾指针
}LinkQueue;
//初始化
Status InitQueue(LinkQueue *Q)
{
QueuePtr l = (QueuePtr)malloc(sizeof(QNode));//生成一个头结点
l->next = NULL;
Q->front = l;
Q->rear = l;
return true;
}
//插入元素e为Q的新的队列元素
Status EnQueue(LinkQueue *Q, QElemType e)
{
QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
if (!s)
exit(OVERFLOW);
s->data = e;
s->next = NULL;
Q->rear->next = s;//将新结点赋值给原队尾结点的后继
Q->rear = s;
return true;
}
//出队操作
Status DeQueue(LinkQueue *Q, QElemType *e)
{
QueuePtr p;//定义一个指针
p = Q->front->next;//p指向欲删除的队头结点
*e = p->data;//将欲删除的队头结点的值赋给e
Q->front->next = p->next;
while (p == Q->rear)//若队头就是队尾,则删除后将rear指向头结点
{
Q->rear = Q->front;
}
free(p);
return true;
}
//遍历输出
Status TraverQueue(LinkQueue Q)
{
while (Q.front != Q.rear)
{
cout << Q.front->next->data << " ";
Q.front = Q.front->next;
}
cout << endl;
return true;
}
int main()
{
LinkQueue Q;
InitQueue(&Q);//初始化
for (int i = 0; i < MAXSIZE; i++)
{
EnQueue(&Q, i);//插入元素
}
TraverQueue(Q);//遍历输出
int e;
DeQueue(&Q,&e);//出队
TraverQueue(Q);//遍历输出
system("pause");
return 0;
}
本人是小白,如有错误,请指正,谢谢。