一、参考知识
二、代码部分
1. 头文件:circular_queue.h
//
// Project: Circular_Queue
// File: circular_queue.h
// IDE: CLion
// Created by RichardLau_Cx on 2021/5/19.
//
/*************************************************************
循环队列操作的实现 头文件
**************************************************************/
//#ifndef CIRCULAR_QUEUE_CIRCULAR_QUEUE_H
//#define CIRCULAR_QUEUE_CIRCULAR_QUEUE_H
//
//#endif //CIRCULAR_QUEUE_CIRCULAR_QUEUE_H
#define MAXQSIZE 100 // 定义循环队列的最大长度
typedef struct {
int *base; // 循环队列的存储空间,假设队列中存放的是整型数
int front; // 指示队头,称为队头指针
int rear; // 指示队尾,称为队尾指针
}SqQueue;
// 创建空的循环队列
int InitQueue(SqQueue *Q);
// 元素入循环队列
int EnQueue(SqQueue *Q, int e);
// 元素出循环队列
int DelQueue(SqQueue *Q, int *e);
// 展示队列
void ShowQueue(SqQueue *Q);
2. 主函数文件:main.cpp
//
// Project: Circular_Queue
// File: functional_operation.cpp
// IDE: CLion
// Created by RichardLau_Cx on 2021/5/19.
//
#include <iostream>
#include "circular_queue.h"
int main() {
SqQueue Q; // 定义全局循环队列
int opt; // 功能选项
int goOn=1; // 是否继续使用
int e; // 元素值
while (goOn) {
printf("\n欢迎来到循环队列的世界,请选择你想要的操作:\n"
"1. 创建一个空的循环队列\n"
"2. 特定元素入队循环队列\n"
"3. 出队循环队列\n"
"4. 展示当前循环队列中的存储情况\n\n");
scanf("%d", &opt);
switch (opt) {
case 1:
InitQueue(&Q); // 传入地址,给指针变量接收
break;
case 2:
printf("\n要入队的元素值:");
scanf("%d", &e);
EnQueue(&Q, e);
break;
case 3:
DelQueue(&Q, &e);
break;
case 4:
ShowQueue(&Q);
break;
}
std::cout << "\n还要继续使用吗(是为1,否为0)?\n" << std::endl;
scanf("%d", &goOn);
}
return 0;
}
3. 功能操作文件:functional_operation.cpp
//
// Project: Circular_Queue
// File: functional_operation.cpp
// IDE: CLion
// Created by RichardLau_Cx on 2021/5/19.
//
#include "circular_queue.h"
#include <cstdlib>
#include <stdio.h>
int InitQueue(SqQueue *Q)
{ // 创建容量为MAXQSIZE的空队列,若成功返回0,否则返回-1
Q->base = (int *)malloc(MAXQSIZE * sizeof(int));
if (!Q->base)
{ // 存储空间分配失败
return -1;
}
Q->front = 0;
Q->rear = 0;
printf("循环队列成功创建!\n");
return 0;
}
int EnQueue(SqQueue *Q, int e)
{ // 元素e入队,若成功,则返回0,否则返回-1
if ((Q->rear+1) % MAXQSIZE == Q->front) // 尾指针的下一个位置为头指针
{ // 循环队列已满
return -1;
}
Q->base[Q->rear] = e; // 用数组代替指针赋值(此时Q->rear相当于索引)
Q->rear = (Q->rear + 1) % MAXQSIZE;
return 0;
}
int DelQueue(SqQueue *Q, int *e)
{ // 若队列不空,则删除队头元素,由参数e带回其值,并且返回0,否则返回-1
if (Q->rear == Q->front) // 尾指针和头指针在同一个位置
{ // 循环队列为空
return -1;
}
*e = Q->base[Q->front]; // 给e赋值
Q->front = (Q->front + 1) % MAXQSIZE; // 头指针后移,即为“删除元素”,实则值还在,等新值值进来时,进行覆盖处理
printf("循环队列元素成功出队!");
return 0;
}
void ShowQueue(SqQueue *Q)
{ // 若队列不为空,展示当前循环中的存储情况
if (Q->rear == Q->front)
{
return;
}
// 从队头遍历到队尾
for (int i = Q->front; i < Q->rear; ++i)
{
printf("%d ", Q->base[i]);
}
}