数据结构----循环队列 (C语言描述)

ps: 值得注意的是当使用 q->rear +1) % MAXSIZE == q->front  条件判断队列是否满时需要牺牲一个单位的存储空间,也就是说当 MAXSIZE 定义为4时队列只能存储3个元素。

队列已满:当尾指针 rear指向第四的存储空间时(第四个存储空间不存放元素)我们就可以判定当前队列已满。

 

队列为空:front 指针与rear指针都指向同一个存储空间时即可判定当前队列为空。

/*
time: 2021-10-24
author: ANJUN
*/
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 4
#define SUCCESS 1
#define ERROR 0

typedef int status;
typedef int ElemType;

typedef struct{
	
	ElemType *base;
	int front;	//队头 
	int rear;	//队尾 
	
}Queue;

/*初始化队列*/ 
status initQueue(Queue *q); 

/*入队操作 */
status in_Queue(Queue *q,ElemType e);

/*出队列操作 */
status out_Queue(Queue *q,ElemType *e);

/*判断队列是否为空 */
int is_emptyQueue(Queue *q);

/*判断队列是否已满 */
int is_fullQueue(Queue *q);
  
/*遍历队列*/
int showQueue(Queue *q);


int main()
{
	
	Queue q;
	ElemType e;
	
	initQueue(&q);
	
	/*1,2,3 入队*/		
	in_Queue(&q,1);
	in_Queue(&q,2);
	in_Queue(&q,3);
	
	printf("遍历队列: ");
	showQueue(&q);
	putchar('\n');
	
	/*一次队列*/
	out_Queue(&q,&e);
	
	printf("遍历队列: ");
	showQueue(&q);
	putchar('\n');
	
	/*两次次队列*/
	out_Queue(&q,&e);
	out_Queue(&q,&e);
	
	return 0;
}




status initQueue(Queue *q)
{
	q->base = (ElemType *)malloc(sizeof(ElemType) * MAXSIZE);    //动态申请内存空间 
	
	if(!q->base )
	{
		printf("内存空间申请失败");
		return ERROR;	
	}
	q->front = q->rear = 0;
	
	return SUCCESS;
}

status in_Queue(Queue *q,ElemType e)
{
	if((q->rear +1) % MAXSIZE == q->front )  //判断队列是否已满 
	{
		printf("队列已满\n");
		return ERROR;
	}
	
	printf("元素 %d 已入队\n",e); 
	
	q->base[q->rear ] = e;
	q->rear = (q->rear +1) % MAXSIZE;    //rear 后移 
	
}

status out_Queue(Queue *q,ElemType *e)
{
	if(q->front == q->rear ) //判断队列是否为空 
	{
		printf("队列为空\n");
		return ERROR; 
	}
	
	printf("队列元素: %d 出队\n",q->base[q->front]);
	
	*e = q->base[q->front];
	q->front = (q->front +1 ) % MAXSIZE;
	return SUCCESS;
}


int is_emptyQueue(Queue *q)
{
	if(q->front == q->rear)
	{
		return 1;
	}else
	{
		return 0;	
	}	
} 

int is_fullQueue(Queue *q)
{
	if((q->rear +1) % MAXSIZE == q->front)
	{
		return 1;
	}else
	{
		return 0;
	}
}

int showQueue(Queue *q)
{
	int i,j;
	i = q->front;
	j = q->rear;
	if(i==j)
	{
		printf("队列为空\n");
		return 0; 
	} 
	while(i<j)
	{
		printf("  %d  ",q->base[i]);
		i++;
	}
	return 1;
} 

效果图:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值