循环队列干净利落实现

介绍:本来是打算不添加任何打印说明的,怕有的人看不懂,所以加了一下。

初学这可以复制去运行一下分析每个函数是怎么实现的

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

#define Elemtype int
#define MAX_QUEUE 8//最大数量为8个 
typedef struct Queue{
	Elemtype *base;//基地址 
	int front;//队头头 
	int tail;//队尾 
}Queue;

void InitQueue(Queue *Q)//初始化队列 
{
	Q->base=(Elemtype*)malloc(sizeof(Elemtype)*MAX_QUEUE);
	Q->front=Q->tail=0;
}

void EnQueue(Queue *Q,Elemtype x)//入队 
{
	if((Q->tail+1)%MAX_QUEUE==Q->front)
		{
		printf("已满\n");
		return;
		}
	Q->base[Q->tail]=x;
	Q->tail=(Q->tail+1)%MAX_QUEUE;
	printf("%d已经入队\n",x); 
}

void show(Queue *Q)//展示队列 
{
	for(int i=Q->front;i!=Q->tail;)
	{
	
	printf("%d  ",Q->base[i]);
	i=(i+1)%MAX_QUEUE;
	}
	
	printf("\n");
}
void DeQueue(Queue *Q)//出队 
{	printf("%d出队\n",Q->base[Q->front]);
	Q->front=(Q->front+1)%MAX_QUEUE;
}
int lenQueue(Queue *Q) 
{
	return (Q->tail-Q->front);
}
void Gethead(Queue *Q,Elemtype *x)//获取对头元素 
{
if(Q->front==Q->tail)
	return;
	
	*x=Q->base[Q->front];
}
void ClearQueue(Queue *Q)//清空 
{
	Q->front=Q->tail=0;
}
void DestroyQueue(Queue *Q)//销毁 
{
	ClearQueue(Q);
	free(Q->base);
	Q->base=NULL;
}

int main()
{	int x;
	Queue Q;
	InitQueue(&Q);
	EnQueue(&Q,1);
	EnQueue(&Q,2);
	EnQueue(&Q,3);
	EnQueue(&Q,4);
	DeQueue(&Q);
	show(&Q);
	printf("队列长%d\n",lenQueue(&Q));
	Gethead(&Q,&x);
	printf("队头元素为%d\n",x);
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵药师

嘿嘿嘿

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值