[Data Structure] Basic operations of circular queue (C++)


Preface

This article mainly introduces the basic operations of circular queues in data structures.


1. Define the queue

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

2. Basic operations of queues

1.Initialize the queue

//初始化队列
void Init_Quene(Quene& s)
{
    
    
	s.front = s.rear = 0;
}

2. Determine if the team is full

//判断队是否为满 返回1为满 返回0为空
int is_Full_Quene(Quene s)
{
    
    
	if ((s.rear + 1) % MAXSIZE == s.front)
	{
    
    
		return 1;
	}
	return 0;
}

3. Joining the team operation

//入队操作
void Push_Quene(Quene& s,int e)
{
    
    
	if (is_Full_Quene(s))
		return;
	s.data[s.rear] = e;
	s.rear = (s.rear + 1) % MAXSIZE;
}

4. Dequeue operation

//出队操作
void Pop_Quene(Quene& s, int& e)
{
    
    
	if (s.front == s.rear)
	{
    
    
		return;
	}
	e = s.data[s.front];
	s.front = (s.front + 1) % MAXSIZE;
}

5. Determine the number of elements in the team

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

All source code

#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;
}

Guess you like

Origin blog.csdn.net/weixin_63614711/article/details/127994748