循环队列
Posted paulversion
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了循环队列相关的知识,希望对你有一定的参考价值。
circleQeueu.h 头文件
#define MAXQSIZE 3
#define OK 1
#define ERROR 0
typedef struct {
int *base;
int front;
int rear;
}Queue;
typedef int Status;
//初始化一个队列
Status InitQueue(Queue *Q);
//获取队列中元素的个数
int QueueLength(Queue Q);
//向队列队尾插入元素
Status EnQueue(Queue *Q, int e);
//删除队头元素
Status DeQueue(Queue *Q,int *e);
//查看队列中的所有元素
Status QueueTraverse(Queue Q);
---------------------------------------------------------------------------------
circleQeueu.c
#include "stdio.h"
#include "stdlib.h"
#include "circleQueue.h"
void main() {
Queue Q;
int length,e;
//初始化队列
InitQueue(&Q);
EnQueue(&Q,1);
EnQueue(&Q,2);
//EnQueue(&Q,4);
length = QueueLength(Q);
//printf("%d\n",length);
QueueTraverse(Q);
printf("删除对头元素\n");
DeQueue(&Q,&e);
QueueTraverse(Q);
printf("插入元素\n");
EnQueue(&Q, 3);
QueueTraverse(Q);
printf("删除对头元素\n");
DeQueue(&Q, &e);
printf("插入元素\n");
EnQueue(&Q, 4);
QueueTraverse(Q);
}
//初始化队列
Status InitQueue(Queue *Q) {
Q->base = (int *)malloc(MAXQSIZE*sizeof(int));//开辟一定长度的空间
if (Q->base == NULL) exit(2);
Q->front = Q->rear = 0;//下标从0开始
return OK;
}
//获取队列中元素的个数
int QueueLength(Queue Q) {
return (Q.rear - Q.front + MAXQSIZE)%MAXQSIZE;
}
//向队列队尾插入元素
Status EnQueue(Queue *Q, int e) {
//判断队列是否已满
//队尾指针始终指向队列尾元素的下一个元素(并没有物理意义上的满)
if ((Q->rear + 1) % MAXQSIZE == Q->front) {
printf("队列已满\n");
return ERROR;
}
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXQSIZE;
return OK;
}
//删除队头元素
Status DeQueue(Queue *Q, int *e) {
//队列为空
if (Q->front == Q->rear) return ERROR;
*e = Q->base[Q->front];
Q->front = (Q->front + 1) % MAXQSIZE;
return OK;
}
Status QueueTraverse(Queue Q) {
if (Q.front == Q.rear) {
printf("队列为空\n");
return OK;
}
while (Q.base[Q.front]!=NULL&&Q.front!=Q.rear)
{
printf("%d\n",Q.base[Q.front]);
Q.front = (Q.front + 1) % MAXQSIZE;
}
}
以上是关于循环队列的主要内容,如果未能解决你的问题,请参考以下文章