循环队列(顺序存储)

循环队列结构定义

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #define SIZE 10
 5 #define OK 1
 6 #define False -1
 7 //循环队列结构定义
 8 typedef struct
 9 {
10     int *base;
11     int front;//相当于循环队列数列的下角标
12     int rear;
13 }CycleQueue;

初始化

1 //队列初始化
2 int InitCycleQueue ( CycleQueue *Q)
3 {
4     Q->base=(int*)malloc(SIZE*sizeof( int));
5     if(!Q->base)
6         exit(0);
7     Q->front=Q->rear=0;
8 }

入队

 1 //入队
 2 
 3 int CreateCycleQueue(CycleQueue *Q,char e)
 4 {
 5     if((Q->rear+1)%SIZE==Q->front)
 6         return False;
 7     Q->base[Q->rear]=e;
 8     Q->rear=(Q->rear+1)%SIZE;//入队后rear指针向后移一位,之所以%是因为若到最后则转到数组头部
 9     return OK;
10 }

出队

 1 //出队
 2  int OutCycleQueue(CycleQueue *Q,int b)
 3  {
 4      char a;
 5      if(Q->front==Q->rear)
 6          return False;
 7      a=Q->base[Q->front];
 8      if(b==1)
 9          printf("%c",a);
10       
11      Q->front=(Q->front+1)%SIZE;
12     
13      return OK;
14  }
 

销毁队列(注意相应元素的归零)

1 //销毁循环队列
2  int DestroyCycleQueue(CycleQueue *Q)
3  {
4      if(Q->base)
5          free(Q->base);//1.空间的释放
6      Q->base=NULL;//2.指针的归零
7      Q->front=Q->rear=0;//3.数据的归零
8      return OK;
9  }

打印队列

1 //打印队列
2  int PrintCycleQueue(CycleQueue *Q)
3  {
4      int i;
5      for(i=Q->front;i<=Q->rear;i++)
6          printf("%c",Q->base[i]);
7      return OK;
8  }

判空

1 //判空
2  int EmptyCycleQueue(CycleQueue *Q)
3  {
4      if(Q->front==Q->rear)
5          return OK;
6  }

主函数测试

 1  //主函数测试
 2  int main()
 3  {
 4      CycleQueue Q;
 5     if( InitCycleQueue ( &Q))
 6         printf("初始化成功!\n");
 7 
 8     if(EmptyCycleQueue(&Q));
 9     printf("队列为空!\n");
10     printf("入队序列:\n");
11      CreateCycleQueue(&Q,'a');
12      CreateCycleQueue(&Q,'b');
13      CreateCycleQueue(&Q,'c');
14      PrintCycleQueue(&Q);
15      printf("\n一个出队:\n");
16       OutCycleQueue(&Q,1);
17       printf("\n再次入队def:\n");
18     CreateCycleQueue(&Q,'d');
19      CreateCycleQueue(&Q,'e');
20      CreateCycleQueue(&Q,'f');
21       PrintCycleQueue(&Q);
22       if( DestroyCycleQueue(&Q))
23           printf("\n已销毁");
24  }

猜你喜欢

转载自www.cnblogs.com/YOLO-in-the-sun/p/12901846.html