数据结构之循环队列

文章目录

队列

循环队列

在队列的顺序存储中,采用出队的方式 , 是删除 front 所指的元素,然后加 1 并返回被删元素。这样可以避免元素 移动,但是也带来了一个新的问题“假溢出” , 使前面的内存不能再次使用。

在这里插入图片描述

能否利用前面的空间继续存储入队呢?采用循环队列

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dChS3Yi6-1665318817142)(D:\冲击offer\博客\数据结构\assets\image-20221009203002338.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JYGioRFx-1665318817142)(D:\冲击offer\博客\数据结构\assets\image-20221009203112706.png)]

演示代码:

#include<iostream>
using namespace std;
//循环队列

//最大存储数
const int MAX = 5;
//模拟存储的数据类型
typedef int dataType;

//队列结构体
struct MyQueue
{
	dataType data[MAX];
	int front;	//指向队头
	int rear;	//指向队尾
};

//初始化队列
void initQueue(MyQueue & myQueue)
{
	myQueue.front = myQueue.rear = 0;
}
//判断队列是否已经满了
bool fullQueue(MyQueue & myQueue)
{
	if ( (( myQueue.rear + 1 ) % MAX) == myQueue.front )
	{
		return true;
	}
	return false;
}

//入队
void pushQueue(MyQueue & myQueue , dataType value)
{
	if (fullQueue(myQueue))
	{
		cout << "队列已满不可再次插入" << endl;
		return;
	}
	myQueue.data[myQueue.rear] = value;
	myQueue.rear = (myQueue.rear + 1) % MAX;
}
//判断队列是否为空
bool emptyQueue(MyQueue & myQueue)
{
	if (myQueue.rear == myQueue.front)
	{
		return true;
	}
	return false;
}

//弹出队头元素
void pushQueue(MyQueue & myQueue)
{
	if (emptyQueue(myQueue))
	{
		cout << "队列为空" << endl;
		return;
	}
	myQueue.front = (myQueue.front + 1) % MAX;
}

//遍历队列
void printQueue(MyQueue & myQueue)
{
	if (emptyQueue(myQueue))
	{
		cout << "队列为空" << endl;
		return;
	}

	int temp = myQueue.front;

	while (temp != myQueue.rear)
	{
		cout << myQueue.data[temp] << endl;
		temp = (temp + 1) % MAX;
	}
}
int main()
{
	MyQueue myQueue;

	//队列初始化
	initQueue(myQueue);

	//队列添加元素
	for (int i = 0; i < 7; i++)
	{
		pushQueue(myQueue, i);
	}
	//打印队列元素
	printQueue(myQueue);


	system("pause");
	return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值