当前位置:   article > 正文

【数据结构】循环队列的基本操作(C++)

循环队列的基本操作


前言

本文主要介绍数据结构中有关循环队列的基本操作


一、定义队列

#define MAXSIZE 100
typedef struct Queue
{
	int data[MAXSIZE];//存储数据
	int front;//指向开头的指针
	int rear;//指向结尾后一个位置的指针
}Quene;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

二、队列的基本操作

1.初始化队列

//初始化队列
void Init_Quene(Quene& s)
{
	s.front = s.rear = 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5

2、判断队满

//判断队是否为满 返回1为满 返回0为空
int is_Full_Quene(Quene s)
{
	if ((s.rear + 1) % MAXSIZE == s.front)
	{
		return 1;
	}
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3、入队操作

//入队操作
void Push_Quene(Quene& s,int e)
{
	if (is_Full_Quene(s))
		return;
	s.data[s.rear] = e;
	s.rear = (s.rear + 1) % MAXSIZE;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

4、出队操作

//出队操作
void Pop_Quene(Quene& s, int& e)
{
	if (s.front == s.rear)
	{
		return;
	}
	e = s.data[s.front];
	s.front = (s.front + 1) % MAXSIZE;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5、判断队内元素个数

//判断队内的元素个数
int length_Quene(Quene s)
{
	return (s.rear - s.front + MAXSIZE) % MAXSIZE;
}
  • 1
  • 2
  • 3
  • 4
  • 5

所有源码

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct Queue
{
	int data[MAXSIZE];
	int front;
	int rear;
}Quene;
//初始化队列
void Init_Quene(Quene& s)
{
	s.front = s.rear = 0;
}
//判断队是否为满 返回1为满 返回0为空
int is_Full_Quene(Quene s)
{
	if ((s.rear + 1) % MAXSIZE == s.front)
	{
		return 1;
	}
	return 0;
}
//入队操作
void Push_Quene(Quene& s,int e)
{
	if (is_Full_Quene(s))
		return;
	s.data[s.rear] = e;
	s.rear = (s.rear + 1) % MAXSIZE;
}
//出队操作
void Pop_Quene(Quene& s, int& e)
{
	if (s.front == s.rear)
	{
		return;
	}
	e = s.data[s.front];
	s.front = (s.front + 1) % MAXSIZE;
}
//判断队内的元素个数
int length_Quene(Quene s)
{
	return (s.rear - s.front + MAXSIZE) % MAXSIZE;
}
int main()
{
	Quene s;
	Init_Quene(s);
	/*if (!is_Full_Quene(s))
	{
		cout << "队列不满" << endl;
	}*/
	cout << "队列中的元素个数为:" << length_Quene(s) << endl;
	Push_Quene(s, 1);
	Push_Quene(s, 2);
	Push_Quene(s, 3);
	cout << "队列中的元素个数为:" << length_Quene(s) << endl;
	int e = 0;
	Pop_Quene(s,e);
	cout << "弹出的元素为:" << e << endl;
	cout << "队列中的元素个数为:" << length_Quene(s) << endl;



	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/867293
推荐阅读
相关标签
  

闽ICP备14008679号