循环队列(c语言实现)

存储结构

//循环队列的顺序存储结构
typedef struct {
	QElemType data[MAXSIZES];
	int front;	// 头指针 
	int rear;	// 尾指针,若队列不为空,指向队列元素的下一个位置 
}SqQueue;

初始化操作

//初始化一个空队列Q
Status InitQueue(SqQueue *Q)
{
	Q->front = Q->rear = 0;
	return OK;
}

求队长

//返回Q的元素个数,也就是队列的当前长度
int QueueLength(SqQueue Q)
{
	return (Q.rear - Q.front + MAXSIZES) % MAXSIZES;
}

入队操作


//入队操作
Status EnQueue(SqQueue *Q, QElemType e)
{
	if ((Q->rear + 1) % MAXSIZES == Q->front)	// 队列满的判断
		return ERROR;
	Q->data[Q->rear] = e;						// 将元素e赋值给队尾 
	Q->rear = (Q->rear + 1) % MAXSIZES;			// rear指针向后移动一个位置
												// 若到最后则转到数组头部 
	
	return OK;
}

出队操作


//出队操作
Status DeQueue(SqQueue *Q, QElemType *e)
{
	if (Q->front == Q->rear)	// 队列空的判断
		return ERROR;
	*e = Q->data[Q->front];
	Q->front = (Q->front + 1) % MAXSIZES;
	
	return OK; 
}

实验结果

在这里插入图片描述

完整的代码

#include <stdio.h>

#define Status int
#define OK 1
#define ERROR 0
#define MAXSIZES 10
typedef int QElemType;

//循环队列的顺序存储结构
typedef struct {
	QElemType data[MAXSIZES];
	int front;	// 头指针 
	int rear;	// 尾指针,若队列不为空,指向队列元素的下一个位置 
}SqQueue;

//初始化一个空队列Q
Status InitQueue(SqQueue *Q)
{
	Q->front = Q->rear = 0;
	return OK;
}

//返回Q的元素个数,也就是队列的当前长度
int QueueLength(SqQueue Q)
{
	return (Q.rear - Q.front + MAXSIZES) % MAXSIZES;
}

//入队操作
Status EnQueue(SqQueue *Q, QElemType e)
{
	if ((Q->rear + 1) % MAXSIZES == Q->front)	// 队列满的判断
		return ERROR;
	Q->data[Q->rear] = e;						// 将元素e赋值给队尾 
	Q->rear = (Q->rear + 1) % MAXSIZES;			// rear指针向后移动一个位置
												// 若到最后则转到数组头部 
	
	return OK;
}

//出队操作
Status DeQueue(SqQueue *Q, QElemType *e)
{
	if (Q->front == Q->rear)	// 队列空的判断
		return ERROR;
	*e = Q->data[Q->front];
	Q->front = (Q->front + 1) % MAXSIZES;
	
	return OK; 
}

int main()
{
	SqQueue q;
	InitQueue(&q);
	printf("队列初始化成功!!!\n");
	printf("插入2 4 6...\n"); 
	EnQueue(&q, 2); 
	EnQueue(&q, 4);
	EnQueue(&q, 6);
	printf("插入成功,队列长度为 %d\n", QueueLength(q));
	int a = 0, b = 0, c = 0;
	DeQueue(&q, &a);
	DeQueue(&q, &b);
	DeQueue(&q, &c);
	printf("队列中的元素为 %d %d %d\n", a, b, c); 
	
	return 0;
}

参考:
《大话数据结构》程杰著

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值