/*************************************************
*
* file name:DoubleDoubleCirLkList.c
* author :[email protected]
* date :2024/04/28
* brief :构建顺序循环队列的接口
* note :None
*
* CopyRight (c) 2024 [email protected] All Right Reseverd
*
**************************************************/
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
/*************************************************
*
* func name :
* brief :
* func parameter:
*
*
* return :None
* note :None
* func author :[email protected]
* date :2024/04/28
* version :V1.0
**************************************************/
// 构建顺序循环队列的结构体(队首下标+队尾下标+队列容量+队列首地址)
typedef int DataType_t;
typedef struct CirculaQueue
{
DataType_t *Addr;
int Front;
int Rear;
unsigned Size;
} CirQueue_t;
// 创建一个顺序循环队列,并对其进行初始化
CirQueue_t *CirQueue_Creat(unsigned int size)
{
// 为循环队列的管理结构体申请内存空间
CirQueue_t *Manager = (CirQueue_t *)calloc(1, sizeof(CirQueue_t));
if (NULL == Manager)
{
perror("calloc memory for Manager is failed!\n");
exit(-1);
}
// 为存储新队列的每个元素申请内存空间
Manager->Addr = (DataType_t *)calloc(size, sizeof(DataType_t));
if (NULL == Manager)
{
perror("calloc memory for Addr is failed!\n");
free(Manager);
exit(-1);
}
// 初始化循环队列
Manager->Size = size;
Manager->Front = 0;
Manager->Rear = 0;
return Manager;
}
// 判断队列是否为空
bool CirQueue_IsEmpty(CirQueue_t *Head)
{
return (Head->Front == Head->Rear) ? true : false;
}
// 判断队列是否已满
bool CirQueue_IsFull(CirQueue_t *Head)
{
return (Head->Front == (Head->Rear + 1) % Head->Size) ? true : false;
}
// 入队操作
bool CirQueue_Enqueue(CirQueue_t *Head, DataType_t data)
{
if (CirQueue_IsFull(Head))
{
printf("the CirQueue is full,Enqueue %d false!\n", data);
return false;
}
Head->Addr[Head->Rear] = data;
Head->Rear = (Head->Rear + 1) % Head->Size;
return true;
}
// 出队操作
DataType_t CirQueue_Dequeue(CirQueue_t *Head)
{
if (CirQueue_IsEmpty(Head))
{
printf("the CirQueue is empty!\n");
return;
}
DataType_t temp = 0;
Head->Front = (Head->Front + 1) % Head->Size;
return temp;
}
// 遍历顺序循环队列的元素
bool CirQueue_Print(CirQueue_t *Head)
{
if (CirQueue_IsEmpty(Head))
{
printf("the CirQueue is empty!\n");
return false;
}
for (int i = 0; i < (Head->Rear + Head->Size - Head->Front) % Head->Size; i++)
{
printf("%d ", Head->Addr[(Head->Front + i) % Head->Size]);
}
printf("\n");
return true;
}
int main(void)
{
CirQueue_t *Head = CirQueue_Creat(11);
CirQueue_Enqueue(Head, 1);
CirQueue_Enqueue(Head, 2);
CirQueue_Enqueue(Head, 3);
CirQueue_Enqueue(Head, 4);
CirQueue_Enqueue(Head, 5);
CirQueue_Enqueue(Head, 6);
CirQueue_Enqueue(Head, 7);
CirQueue_Enqueue(Head, 8);
CirQueue_Enqueue(Head, 9);
CirQueue_Enqueue(Head, 10);
CirQueue_Enqueue(Head, 11);
CirQueue_Print(Head);
CirQueue_Dequeue(Head);
CirQueue_Print(Head);
return 0;
}
标签:Head,顺序,return,队列,接口,Enqueue,Manager,CirQueue
From: https://www.cnblogs.com/bell-c/p/18164752