一、代码如下
/*
项目名称:链循环队列的建立与基本操作
编译环境:VC++ 2008
作者相关:。。。
最后修改:2019.6.26
学习目标:初始化、销毁、清空、判空、求长、返回队头元素、插入元素、删除元素、输出队列中元素
注意事项:1.测试所有功能是否正常
2.front始终指向头结点而不是首元素,rear始终指向尾元素
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ERROR 0
#define OK 1
typedef int ElemType;
typedef bool Status;
//定义结点
typedef struct QNode{
ElemType data;
struct QNode *next;
}QNode,*QNodeptr;
//该结构体含有两个结点指针变量
typedef struct{
QNodeptr front;//队头指针
QNodeptr rear;//队尾指针
}LinkQueue;
Status Init_LQueue(LinkQueue *L);
Status Destroy_LQueue(LinkQueue *L);
Status Clear_LQueue(LinkQueue *L);
Status Empty_LQueue(LinkQueue L);
int Length_LQueue(LinkQueue L);
Status GetHead_LQueue(LinkQueue L,ElemType *e);
Status En_LQueue(LinkQueue *L,ElemType e);
Status De_LQueue(LinkQueue *L,ElemType *e);
void visit(ElemType c);
Status Out_LQueue(LinkQueue L);
int main()
{
LinkQueue L1;
ElemType e;
Init_LQueue(&L1);
for(int i=3;i<13;i++)
En_LQueue(&L1,i);
Out_LQueue(L1);
int k = Length_LQueue(L1);
printf("循环链队列长度为:%d \n\n",k);
GetHead_LQueue(L1,&e);
printf("循环链队列队首元素为:%d \n\n",e);
De_LQueue(&L1,&e);
printf("第一次删除的元素值为:%d \n\n",e);
De_LQueue(&L1,&e);
printf("第二次删除的元素值为:%d \n\n",e);
Out_LQueue(L1);
Clear_LQueue(&L1);
Destroy_LQueue(&L1);
return 0;
}
Status Init_LQueue(LinkQueue *L)
{
L->rear=L->front=(QNodeptr)malloc(sizeof(QNode));//两个指针都指向头结点
if(!L->front)
return ERROR;
L->front->next = L->front;
return OK;
}
Status Destroy_LQueue(LinkQueue *L)
{
QNodeptr p,q;
p = L->front->next;
while(p!=L->front)
{
q = p;
p = p->next;
free(q);
}
free(p);
return OK;
}
Status Clear_LQueue(LinkQueue *L)
{
QNodeptr p,q;
p = L->front->next;
while(p!=L->front)
{
q = p;
p = p->next;
free(q);
}
L->rear = L->front;
L->front->next = L->front;
return OK;
}
Status Empty_LQueue(LinkQueue L)
{
if(L.front->next==L.front)
return true;
else
return false;
}
int Length_LQueue(LinkQueue L)
{
int count=0;
QNodeptr p=L.front;
while(p!=L.rear)
{
++count;
p=p->next;
}
return count;
}
Status GetHead_LQueue(LinkQueue L,ElemType *e)
{
if(Empty_LQueue(L))
return ERROR;
else
*e = L.front->next->data;
return OK;
}
Status En_LQueue(LinkQueue *L,ElemType e)
{
QNodeptr s;
s=(QNodeptr)malloc(sizeof(QNode));
if(!s)
return ERROR;
s->data = e;
s->next = L->front;
L->rear->next = s;
L->rear = s;//rear指向最后一个元素
return OK;
}
Status De_LQueue(LinkQueue *L,ElemType *e)
{
if(Empty_LQueue(*L))
return ERROR;
else
{
*e = L->front->next->data;
L->front->next=L->front->next->next;
}
return 0;
}
void visit(ElemType c)
{
printf("%d ",c);
}
Status Out_LQueue(LinkQueue L)
{
QNodeptr p=L.front->next;
printf("循环链队列内容: ");
while(p!=L.front)
{
visit(p->data);
p=p->next;
}
printf("\n\n");
return 0;
}
二、效果