数据结构实现——循环队列

数据结构实现——循环队列

原创不易,转载请声明出处。

刚学队列,若有BUG,欢迎反馈

使用的函数功能介绍

Queue *Creat(int max);

功能:创建空队列,空队列所能容纳的最大值元素个数是max,返回Queue*,作为该队列的指针。

注意:max必须>=0.

特殊情况:当无法申请空间时,返回NULL。

使用方法:

Queue *Q = Creat(2);

int Destroy(Queue* Q)

功能:删除队列,若成功,返回1;

特殊情况:当队列已经被删除(Q为空指针),返回0。

注意:使用之后,一定要立即将指针置空

int Empty(Queue *Q)

功能:判断是否为空,若为空,这返回1,否则返回0.

int Full(Queue* Q)

功能:判断是否已满,若已满,这返回1,否则返回0.

int Push(Queue *Q, Elem e)

功能:向队列中PUSH一个元素。

特殊情况:若队列已满,这返回0,如果正常push,返回1。

int Pop(Queue *Q)

功能:将队列中POP一个元素。

特殊情况:若队列空,这返回0,如果正常,返回1。

Elem GetHead(Queue *Q)

功能:返回队首元素

特殊情况:若队列为空,则程序crash。

Elem GetTail(Queue *Q)

功能:返回队尾元素

特殊情况:若队列为空,则程序crash。

int Size(Queue* Q)

功能:返回队列中的元素个数

源代码

#include <stdio.h>
#include <stdlib.h>
typedef int Elem;
typedef struct Queue
{
Elem *data;
int head;
int tail;
int size;//仅仅是一个功能,程序的判空,判断满并不依赖。
int MAX_SIZE;//是真正申请的最大值,实际存放MAX_SIZE-1个。
}Queue;
//函数原形声明
Queue *Creat(int max);
int Size(Queue* Q);
Elem GetTail(Queue *Q);
Elem GetHead(Queue *Q);
int Pop(Queue *Q);
int Push(Queue *Q, Elem e);
int Full(Queue* Q);
int Empty(Queue *Q);
int Destroy(Queue* Q);
Queue *Creat(int max)
{
if(max <= 0)
return NULL;
Elem *D = (Elem*)calloc(max + 1, sizeof(Elem));
if(!D)
return NULL;
Queue *Q = (Queue*)malloc(sizeof(Queue));
if(!Q)
{
free(D);
return NULL;
}
Q->MAX_SIZE = max + 1;
Q->data = D;
Q->head = 0;
Q->tail = 0;
Q->size = 0;
return Q;
}
int Destroy(Queue* Q)
{
if(!Q)
return 0;
free(Q->data);
free(Q);
return 1;
}
int Empty(Queue *Q)
{
if(Q->head == Q->tail)
return 1;
else
return 0;
}
int Full(Queue* Q)
{
if((Q->tail+1)%Q->MAX_SIZE == Q->head)
return 1;
else
return 0;
}
int Push(Queue *Q, Elem e)
{
if(Full(Q))
return 0;
Q->data[Q->tail] = e;
Q->tail = (Q->tail + 1)%Q->MAX_SIZE;
Q->size += 1;
return 1;
}
int Pop(Queue *Q)
{
if(Empty(Q))
return 0;
Q->head = (Q->head + 1) % Q->MAX_SIZE;
Q->size -= 1;
return 1;
}
Elem GetHead(Queue *Q)
{
if(Empty(Q))
{
*(int *)NULL;//专门让程序crash
}
return Q->data[Q->head];
}
Elem GetTail(Queue *Q)
{
if(Empty(Q))
{
*(int *)NULL;//专门让程序crash
}
int t;
t = Q->tail;
t -= 1;
if(t >= 0)
return Q->data[t];
else
{
return Q->data[Q->MAX_SIZE-1];
}
}
int Size(Queue* Q)
{
return Q->size;
}
int main()
{
Queue *Q = Creat(2);
printf("size:%d\n",Size(Q));
printf("empty?:%d\n",Empty(Q));
Push(Q,1);
Pop(Q);
Push(Q,1);
printf("empty?:%d\n",Empty(Q));
Push(Q,2);
printf("%d %d\n",GetHead(Q),GetTail(Q));
printf("size:%d\n",Size(Q));
Pop(Q);
Pop(Q);
printf("fault_signal:%d\n",Pop(Q));
Push(Q,2);
printf("Size:%d\n",Size(Q));
Destroy(Q);
Q = NULL;
return 0;
}

更多推荐:
数据结构实现——链队列

posted @   心坚石穿  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示