//循环队列 --- 队列顺序表示和实现
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define MAXQSIZE 5 // 最大队列长度
typedef struct
{
int *base; //初始化的动态分配存储空间
int front; //头指针 若队列不空 指向队列头元素
int rear; //尾指针 若队列不空 指向队尾元素的下一个位置
}SqQueue;
bool InitQueue(SqQueue * q); // 构造一个空队列
void QueueEmpty(SqQueue q); //判断队列是否为空
bool EnQueue(SqQueue *q,int e); //插入元素e为q的新队尾元素
int QueueLength(SqQueue q); //求队列的长度
bool DeQueue(SqQueue *q,int *e); //删除队头元素并用e带回
bool QueueTravese(SqQueue q); //输出队列中的元素
bool GetHead(SqQueue q,int *e); //求队头元素
bool ClearQueue(SqQueue *q); //清空队列
bool DestoryQueue(SqQueue *q); //销毁队列
int main()
{
int j;
int i = 0, l;
int d;
SqQueue q;
InitQueue(&q); //队列的初始化
QueueEmpty(q); //判断队列是否为空
printf("请输入整形队列元素(不超过 %d个)-1 为提前结束符:\n",MAXQSIZE-1);
/*
do
{
scanf("%d",&d);
if(d == -1)
break;
i++;
EnQueue(&q,d);
}while(i < MAXQSIZE - 1);
*/
for(; i < MAXQSIZE - 1; i++)
{
scanf("%d",&d);
if(d == -1)
break;
EnQueue(&q,d);
}
printf("队列的长度为%d\n",QueueLength(q));
QueueEmpty(q); //判断队列是否为空
printf("连续%d次由队头删除元素,队尾插入元素\n",MAXQSIZE);
for(l = 1; l <= MAXQSIZE; l++)
{
DeQueue(&q,&d);
printf("删除的元素是%d,请输入待插入元素:",d);
scanf("%d",&d);
EnQueue(&q,d);
}
l = QueueLength(q);
printf("现在队列中的元素为 :\n");
QueueTravese(q);
GetHead(q,&d);
printf("现在队头元素为:%d\n",d);
ClearQueue(&q); //清空队列
printf("清空队列后 队列是否为空!");
QueueEmpty(q);
DestoryQueue(&q);
return 0;
}
bool InitQueue(SqQueue * q) // 构造一个空队列
{
q->base = (int *)malloc(MAXQSIZE*sizeof(int));
if(q->base == NULL)
{
printf("内存分配失败 程序终止");
exit(-1);
}
q->front = q->rear = 0;
return true;
}
void QueueEmpty(SqQueue q) //判断队列是否为空
{
if(q.front == q.rear)
printf("队列为空\n");
else
printf("队列不为空\n");
}
bool EnQueue(SqQueue *q,int e) //插入元素e为q的新队尾元素
{
if((q->rear+1)%MAXQSIZE == q->front) //队列满
return false;
q->base[q->rear] = e;
q->rear = (q->rear+1)%MAXQSIZE;
return true;
}
int QueueLength(SqQueue q) //求队列的长度
{
return (q.rear - q.front + MAXQSIZE) % MAXQSIZE;
}
bool DeQueue(SqQueue *q,int *e) //删除队头元素并用e带回
{
if(q->front == q->rear)
return false;
*e = q->base[q->front];
q->front = (q->front + 1) % MAXQSIZE;
return true;
}
bool QueueTravese(SqQueue q) //输出队列中的元素
{
int i;
i = q.front;
while(i != q.rear)
{
printf("%d ",q.base[i]);
i = (i+1)%MAXQSIZE;
}
printf("\n");
return true;
}
bool GetHead(SqQueue q,int *e) //求队头元素
{
if(q.front == q.rear) //队列空
return false;
*e = q.base[q.front];
return true;
}
bool ClearQueue(SqQueue *q) //清空队列
{
q->front = q->rear = 0;
return true;
}
bool DestoryQueue(SqQueue *q) //销毁队列
{
if(q->base != NULL)
free(q->base);
q->base = NULL;
q->front = q->rear = 0;
return true;
}
循环队列(C语言实现)
最新推荐文章于 2022-10-03 16:06:24 发布