循环队列程序演示

#define _CRT_SECURE_NO_WARNINGS 1
#define length 6
#include<stdio.h>
#include<malloc.h>


typedef struct queue
{
	int* pBase;
	int front;
	int rear;
}QUEUE;
void init(QUEUE*);//初始化
bool en_queue(QUEUE*, int val);//入队
bool is_full(QUEUE*);//判满
void traverse(QUEUE*);//遍历
bool dequeue(QUEUE*, int*);//出队
bool is_empty(QUEUE*);//判空

int main()
{
	int val;
	QUEUE Q;
	init(&Q);
	en_queue(&Q, 1);
	en_queue(&Q, 2);
	en_queue(&Q, 3);
	en_queue(&Q, 4);
	en_queue(&Q, 5);
	en_queue(&Q, 6);
	en_queue(&Q, 7);
	en_queue(&Q, 8);
	en_queue(&Q, 9);
	traverse(&Q);
	if (dequeue(&Q, &val))
	{
		printf("出队成功,出队的元素是%d\n", val);
	}
	else
		printf("出队失败");
	traverse(&Q);
	return 0;
}

void init(QUEUE* pQ)
{
	pQ->pBase = (int*)malloc(sizeof(int) * length);
	pQ->front = pQ->rear = 0;
}

bool en_queue(QUEUE* pQ, int val)
{
	if (is_full(pQ))
		return false;
	else
	{
		pQ->pBase[pQ->rear] = val;
		pQ->rear = (pQ->rear + 1) % length;
	}
}

bool is_full(QUEUE* pQ)
{
	if ((pQ->rear + 1) % length == pQ->front)
		return true;
	else
		return false;
}

void traverse(QUEUE* pQ)
{
	int p = pQ->front;
	while (p!=pQ->rear)
	{
		printf("%d ", pQ->pBase[p]);
		p = (p + 1) % length;
	}
	printf("\n");
	return;
}

bool dequeue(QUEUE* pQ, int* pVal)
{
	if (is_empty(pQ))
		return false;
	else
	{
		*pVal =pQ->pBase[ pQ->front];
		pQ->front = (pQ->front + 1) % length;
	}
}

bool is_empty(QUEUE* pQ)
{
	if (pQ->front == (pQ->rear))
		return true;
	else
		return false;
}

结果如下

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值