C语言实现循环(顺序)队列的基本操作

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 10
#define TRUE 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct
{
	ElemType *base;  //数组基地址,动态分配内存
	int front;   //头指针
	int rear;      //尾指针
}Queue;
Status InitQueue(Queue* Q);   //初始化
Status InsertQueue(Queue* Q, ElemType e);// 入队
Status DeleteQueue(Queue* Q, ElemType* e); //出队
Status LengthQueue(Queue* Q);  //获取队长
void DstoryQueue(Queue *Q); //销毁队
int main()
{
	Queue Q;
	ElemType e;
	int n, a;
	if (InitQueue(&Q) == 1)
		printf("创建循环队列成功!\n");
	printf("输入插入队尾元素个数:");
	scanf("%d", &n);
	printf("输入插入队尾元素:");
	if (n != 0)      //判断队空
	{
		for (int i = 0; i < n; i++)
		{
			scanf("%d", &e);
			a = InsertQueue(&Q, e);

		}
	}
	else
		a = -1;
	if (a == 1) {
		printf("插入成功!\n");
		printf("队长为:%d\n", LengthQueue(&Q));
	}
		if (a==0)
		printf("队已满!无法继续插入了!\n");
	if (DeleteQueue(&Q, &e) == 1)
	{
		printf("删除队首元素为:%d\n", e);
	}
	else
		printf("队为空!无法继续删除了!\n");
	printf("删除后队长为:%d\n", LengthQueue(&Q));
	DstoryQueue(&Q);
	printf("销毁完毕!");

	return 0;
}
Status InitQueue(Queue* Q)
{
	Q->base = (Queue*)malloc(sizeof(ElemType) * MaxSize);
	if (!Q->base)
		exit(0);
	Q->front = Q->rear = 0;

	return TRUE;
}
Status InsertQueue(Queue *Q, ElemType e)
{
	if ((Q->rear + 1) % MaxSize == Q->front)
		return ERROR;
	Q->base[Q->rear] = e;
	Q->rear = (Q->rear + 1) % MaxSize;

	return TRUE;
}
Status DeleteQueue(Queue* Q, ElemType* e)
{
	if (Q->front == Q->rear)
		return ERROR;
	*e = Q->base[Q->front];
	Q->front = (Q->front + 1) % MaxSize;

	return TRUE;
}
Status LengthQueue(Queue* Q)
{
	return ((Q->rear-Q->front+MaxSize)%MaxSize);
}
void DstoryQueue(Queue* Q)
{
	free(Q->base);
	Q->base = NULL;
	Q->front = Q->rear = 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值