栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

第四期 01季 C/C++数据结构 顺序队列的基本操作(循环队列)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第四期 01季 C/C++数据结构 顺序队列的基本操作(循环队列)

本期关注点当然是我们的队列,队列是先进先出的。

1.从队头出队,队尾入队。

2.判断队列为空的条件:Q.rear==Q.front

3.判断队列为满的条件:(Q.rear+1)%MaxSize==Q.front

4.求取长度:q.rear-q.front

本次实训关注点在于循环队列,将普通的队列尾与头相连操作代码如下:

#include 
using namespace std;
#define MAXSIZE 100

typedef struct {
	char *elem;		//顺序栈动态分配空间
	int front;		//顺序队列先进先出,front做头指针(做删除),rear做尾指针(做插入)
	int rear;
}SqQueue;

void InitSqQueue(SqQueue &q) {
	q.elem = new char[MAXSIZE];					//1.分配空间
	if (!q.elem) cout << "分配空间失败!";		//判断分配空间是否成功
	q.front = q.rear = 0;						//2.队头队尾指针指向0,队列为空
	cout << "初始化成功" << endl;
}
void InsertSqQueue(SqQueue& q) {				//入队操作---入队rear的后面
	cout << "入队操作,请输入入队个数:";
	int n; cin >> n;
	cout << "再输入要入队的元素:";
	for (int i = 0; i < n; i++){
		char e; cin >> e;
		if ((q.rear + 1) % MAXSIZE == q.front) {//判断队列是否已满
			cout << "队列满喽~"; 
		}
		else {									//如果未满,将元素直接放置顺序尾指针下表下
			q.elem[q.rear] = e;
			q.rear = (q.rear + 1) % MAXSIZE;	//循环队列的尾下表+1
		}
	}
}
void DeQueue(SqQueue& q) {
	if (q.front==q.rear){
		cout << "队列是空的,无法出队!";
	}
	else{
		cout << "请输入你要出队元素的个数:";
		int n; cin >> n;
		cout << "出队元素为:";
		for (int i = 0; i < n; i++){
			char e;
			e = q.elem[q.front]; cout << e << " ";
			q.front = (q.front + 1) % MAXSIZE;			//头指针+1
		}
		cout << endl;
	}
}
void LengthSqQueue(SqQueue &q) {
	cout << "顺序栈的长度为:" << (q.rear - q.front + MAXSIZE) % MAXSIZE << endl;;		//循环队列的情况下
	//q.rear - q.front; 非循环队列的情况下
}
void EmptySqQueue(SqQueue& q) {
	if (q.front==q.rear)	{
		cout << "队列是空的!" << endl;
	}
	else {
		cout << "队列不为空!" << endl;
	}
}
void GetHead(SqQueue& q) {
	if (q.front!=q.rear)	{	//队列不为空时 取队列头元素
		cout << "队头元素为:" << q.elem[q.front] << endl;//返回头元素指针下表
	}
	else{
		cout << "队列为空,无头元素!" << endl;
	}
}
int main() {
	SqQueue q;
	cout << "1.初始化:";
	InitSqQueue(q);

	cout << "2.";
	InsertSqQueue(q);

	cout << "3.";
	LengthSqQueue(q);

	cout << "4.";
	GetHead(q);

	cout << "5.";
	DeQueue(q);

	cout << "6.";
	EmptySqQueue(q);
}

代码运行截图:

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/780166.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号