码迷,mamicode.com
首页 > 其他好文 > 详细

循环队列

时间:2017-10-13 20:05:50      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:队列   bsp   amp   lib   stdio.h   status   ret   fine   头文件   

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;

}


}

 

循环队列

标签:队列   bsp   amp   lib   stdio.h   status   ret   fine   头文件   

原文地址:http://www.cnblogs.com/paulversion/p/7662675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!