循环队列

如果使用数组来模拟队列,在出队时,要频繁移动队列中元素,因此使用循环队列来避免这个问题


如果头指针和尾指针所指位置之间的间隔只有一个元素,那么在次入队时,头指针和尾指针将指向同一个位置,这时将无法确定是队满,还是队空

所以解决这个问题的方法有两种:

1.队列中空出一个元素的位置来隔开头尾指针

2.设置一个标识变量flag,当头尾指针指向位置相同时,如果队满flag = 1,队空则flag = 0;

我用第一种方法。

代码如下:

SqQueue.h源文件:

#include<stdio.h>
typedef int ElemType;
#define MAXSIZE 5

typedef struct  
{
	ElemType data[MAXSIZE];
	int rear;//记录当前队列首元素位置
	int front;//记录当前队列尾元素的下一个位置
}SqQueue;

void initQueue(SqQueue * Q);//初始化队列
int  queueLength(SqQueue * Q);//获取队列长度
void enterQueue(SqQueue * Q,ElemType e);//入队
int deQueue(SqQueue *Q);//出队
int getFront(SqQueue *Q);//获取队头元素,但并不出队
void printQueue(SqQueue *Q);//从头至尾打印队列中元素


SqQueue.c源文件:

#include"SqQueue.h"
#include<time.h>
void initQueue(SqQueue * Q)//初始化队列
{
	Q->front = Q->rear = 0;
	printf("Init success!\n");
}
int  queueLength(SqQueue * Q)//获取队列长度
{
	if (Q == NULL)
	{
		printf("Queue is not inition!\n");
		return;
	}
	return (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
}
void enterQueue(SqQueue * Q, ElemType e)//入队
{
	if (Q == NULL)
	{
		printf("Queue is not inition!\n");
		return;
	}
	if ((Q->rear + 1) % MAXSIZE == Q->front)//判断是否队满,余上MAXSIZE是为了rear处于对尾,front处于队头的情况
	{
		printf("Queue is full!\n");
		return;
	}

	Q->data[Q->rear] = e;//入队
	Q->rear = (Q->rear + 1) % MAXSIZE;
}
int deQueue(SqQueue *Q)//出队
{
	if (Q == NULL)
	{
		printf("Queue is not inition!\n");
		return;
	}
	if (Q->front == Q->rear)
	{
		printf("Queue is empty!\n");
		_sleep(3000);
		exit(1);
	}
	int value =  Q->data[Q->front];
	Q->front = (Q->front + 1) % MAXSIZE;
	return value;
}
int getFront(SqQueue *Q)//获取队头元素,但并不出队
{
	if (Q == NULL)
	{
		printf("Queue is not inition!\n");
		_sleep(3000);
		exit(1);
	}
	if (Q->front == Q->rear)
	{
		printf("Queue is empty!\n");
		_sleep(3000);
		exit(1);
	}
	return Q->data[Q->front];
}
void printQueue(SqQueue *Q)//从头至尾打印队列中元素
{
	if (Q == NULL)
	{
		printf("Queue is not inition!\n");
		return;
	}
	if (Q->front == 0 && Q->rear == 0)
	{
		printf("Queue is empty!\n");
		return;
	}

	int pFont = Q->front;
	printf("Print from Queue's front!\n");
	while ((pFont) % MAXSIZE != Q->rear)
	{
		printf("%d	\n", Q->data[pFont++]);
	}

	printf("\n");
}

很简单。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值