循环队列(C语言实现)

//循环队列 --- 队列顺序表示和实现 

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值