数据结构与算法(队列的基本操作)

基本数据结构与算法

(二)队列的实现(循环队列)

一.用数组方式实现

/*队列的结构定义*/
#define Size <队列的最大长度>
typedef struct QNode
{
	int		 MaxSize;//指定数组的长度
	ElemType *Data;//存放数据的数组
	int		 front;//存放队列中头部元素位置的变量
	int		 rear;//存放队列队尾元素位置的变量
}Queue; 
//创建一个空队列
Queue* createQueue(int Size)
{
	/*创建一个指向队列的指针*/
	Queue* Q=(Queue*)malloc(sizeof(Queue));
	//初始化队列
	Q->MaxSize=Size;//数组的长度设为Size
	Q->front=0;//头部位置为0
	Q->rear=0;//尾部位置为0
	return Q;
}

我们让队列中头部位置与尾部位置相等时代表为空
头部与尾部相差为1⃣️时代表队列已满

//判断队列为空
bool isEmpty(Queue* Q)
{
	/*当头部与尾部相等时为空*/
	if(Q->front==Q->rear)
		return true;
	else
		return false;
}
//判断队列是否已满
bool isFull(Queue* Q)
{
	/*当头部与尾部相差为1时代表已满*/
	if((Q->rear+1)%(Q->Maxsize)==Q->front)
		return true;
	else
		return false;
}

队列中入队动作是在队列的尾部进行
而出队动作则在队列的头部进行

//插入元素
void InsertQ(Queue* Q,ElemType item)
{
	/*当队列的尾部与头部相差1时队列已满*/
	if((Q->rear+1)%(Q->MaxSize)==Q->front)
	{
		printf("队列已满");
	}
	else
	{
		/*将尾部向后移动一位*/
		Q->rear=(Q->rear+1)%(Q->Maxsize);
		/*将元素插入队列*/
		Data[Q->rear]=item;
	}
}
//出队操作
ElemType Delete(Queue* Q)
{
	if(Q->rear==Q->front)
	{
		printf("队列已空");
		return NULL;
	}
	else
	{
		/*front总是指向队列中头部元素的前一个位置*/
		Q->front==(Q->front+1)%Maxsize;
		return Q->Data[Q->front];
	}
}
//获取头部元素操作
ElemType Head(Queue *Q)
{
	if(Q->front==Q->rear)
	{
		printf("队列已空");
		return NULL;
	}
	else
	return Q->Data[(Q->front+1)%(Q->MaxSize)];
}
//获取队列长度
int Size(Queue* Q)
{
return (Q->MaxSize+Q->rear-Q-Front)%Q->MaxSize;
}

二.用链表的方式实现

//定义节点
typedef struct Node
{
	ElemType Data;
	Node*	 next;
}QNode;
typedef	struct 
{
	QNode*	front;
	QNode*	rear;
}Queue;
//创建空队列队列
Queue*	createQueue(Queue* Q)
{
	Q->front=(QNode*)malloc(sizeof(QNode));
	Q->front->next=NULL;//对应下图第一步操作
	Q->rear=Q->front;//对应下图第二步操作
	return Q;
}

在这里插入图片描述

//判断队列是否为空
bool isEmpty(Queue* Q)
{
	if(Q->front==Q->rear)
		return true;
	else
		return false;
}
//求队列长度
int Size(Queue* Q)
{
	int i=0;
	QNode *tmp=Q->front->next;//tmp指向队列第一个元素
	/*指针不指向空时,移向下一个节点,i加1*/
	while(tmp)
	{
		i++;
		tmp=tmp->next;
	}
	return i;
}
//读取队列头节点中的元素
ElemType Head(Queue* Q)
{
	if(Q->front==Q->rear)
		printf("队列已空");
		return NULL;
	else
		return Q->front->next->Data;
}
//入队操作
void AddQ(Queue* Q,ElemType Item)
{
	QNode*	s=(QNode*)malloc(sizeof(QNode));
	s->Data=Item;
	s->next=NULL;
	Q->rear->next=s;
	Q->rear=s;
}

在这里插入图片描述

//出队操作
ElemType Delete(Queue* Q)
{
	ElemType elem;
	QNode*	 tmp;
	if(Q->front==Q->rear)
		return NULL;
	else
	{
		tmp=Q->front->next;
		Q->front->next=tmp->next;
		if(tmp->next==NULL)
		Q->rear=Q->front;
		x=tmp->Data;
		free(tmp);
		return x;
	}
	
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值