队列
- 线性存储结构,队列的一边进行删除操作,另外一边进行插入操作(双端队列除外);
- 一般是队头出队(删除),队尾入队(插入);
- 先进先出
- 存储结构可以为顺序结构,也可以为链式结构;
- 类别:顺序队列、链式队列、循环队列、双端队列
循环队列数据结构 C语言
//循环队列数据结构
#define true 1
#define false 0
#define OVERFLOW 1
#define MAXQSIZE 100
typedef struct{
int* base; //初始化的动态分配存储空间
int front; //队头指针
int rear; //队尾指针
}SqQueue;
循环队列方法声明和实现 C语言
- 基本函数声明
void InitQueue(SqQueue*);
//构造一个空的队列
int QueueLength(SqQueue);
//返回队列长度
void EnQueue(SqQueue*, int);
//入队
void DeQueue(SqQueue*, int*);
//出队
void DestoryQueue(SqQueue*);
//销毁队列
int QueueEmpty(SqQueue);
//队空判断
- 基本函数实现
void InitQueue(SqQueue* Q){ //构造一个空的队列
Q->base = (int*)malloc(MAXQSIZE * sizeof(int));
if(!Q->base) return exit(OVERFLOW);
Q->front = Q->rear = 0;
}
int QueueLength(SqQueue Q){ //返回队列长度
return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
void EnQueue(SqQueue* Q, int e){ //入队、插入
if((Q->rear + 1) % MAXQSIZE == Q->front) return exit(OVERFLOW); //队满
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXQSIZE;
}
void DeQueue(SqQueue* Q, int* e){ //出队、删除
if(Q->front == Q->rear) return exit(OVERFLOW); //队空
*e = Q->base[Q->front]; //e是指针,修改指针e指向地址空间的值,需要对*e进行赋值
Q->front = (Q->front + 1) % MAXQSIZE;
}
void DestoryQueue(SqQueue* Q){ //销毁队列
free(Q->base);
free(Q);
}
int QueueEmpty(SqQueue Q){ //判队列是否为空
if(Q.front == Q.rear) return true;
return false;
}
- 循环队列操作的例子
int main(){
int* e = (int*)calloc(1, sizeof(int));
SqQueue* Q = (SqQueue*)malloc(sizeof(SqQueue));
InitQueue(Q);
EnQueue(Q, 21);
EnQueue(Q, 23);
printf("%d\n", QueueLength(*Q)); //2
DeQueue(Q, e);
printf("%d\n", *e); //21
printf("%d\n", QueueLength(*Q)); //1
DeQueue(Q, e);
printf("%d\n", *e); //23
DestoryQueue(Q);
free(e);
return 0;
}
输出结果为
2
21
1
23
参照
严蔚敏 吴伟名 米宁.数据结构(C语言版)[M].出版地:北京 出版社:清华大学出版社,出版年∶2018.