循环队列

循环队列

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<malloc.h>
  4 
  5 typedef struct Queue
  6 {
  7     int * pBase;
  8     int front;
  9     int rear;
 10 }QUEUE;
 11 
 12 void init_Queue(QUEUE *);
 13 bool en_Queue(QUEUE *,int val);   //入队
 14 void traverse_Queue(QUEUE *);
 15 bool full_Queue(QUEUE *);
 16 bool out_Queue(QUEUE *,int*);   //出队
 17 bool empty_Queue(QUEUE *Qu);
 18 
 19 int main(void)
 20 {
 21     QUEUE Q;
 22     int val;
 23 
 24     init_Queue(&Q);
 25 
 26     printf("入队元素是:");
 27     en_Queue(&Q,1);
 28     en_Queue(&Q,2);
 29     en_Queue(&Q,3);
 30     en_Queue(&Q,4);
 31     en_Queue(&Q,5);
 32     en_Queue(&Q,6);
 33     en_Queue(&Q,7);
 34     en_Queue(&Q,8);
 35     traverse_Queue(&Q);
 36 
 37     if( out_Queue(&Q,&val) )
 38     {
 39         printf("
队列出队元素是:%d
",val);    //只是出队一个元素
 40     }
 41     else
 42     {
 43         printf("队列为空");
 44     }
 45     printf("队列元素为:");
 46     traverse_Queue(&Q);  //输出剩余队列元素
 47 
 48     return 0;
 49 }
 50 
 51 void init_Queue(QUEUE *Qu)
 52 {
 53     Qu->pBase = (int *)malloc(sizeof(int)*6);
 54     Qu->front = 0;
 55     Qu->rear = 0;
 56 }
 57 
 58 bool full_Queue(QUEUE *Qu)
 59 {
 60     if( (Qu->rear+1)%6 == Qu->front )
 61     {
 62         return true;
 63     }
 64     else
 65     {
 66         return false;
 67     }
 68 }
 69 
 70 bool en_Queue(QUEUE *Qu,int val)
 71 {
 72     if( full_Queue(Qu) )
 73     {
 74         return false;
 75     }
 76     else
 77     {
 78         Qu->pBase[Qu->rear] = val;
 79         Qu->rear = (Qu->rear+1)%6;
 80         return true;
 81     }
 82 }
 83 
 84 void traverse_Queue(QUEUE *Qu)
 85 {
 86     int i = Qu->front;
 87     while( i != Qu->rear )
 88     {
 89         printf("%d ",Qu->pBase[i]);
 90         i = (i+1)%6;
 91     }
 92     return;
 93 }
 94 
 95  bool empty_Queue(QUEUE *Qu)
 96  {
 97      if(Qu->front == Qu->rear)
 98      {
 99          return true;
100      }
101      else
102      {
103          return false;
104      }
105  }
106 
107 bool out_Queue(QUEUE *Qu,int * pVal)
108 {
109     if( empty_Queue(Qu) )
110     {
111         return false;
112     }
113     else
114     {
115         *pVal = Qu->pBase[Qu->front];
116         Qu->front = (Qu->front+1)%6;
117         return true;
118     }
119 }
原文地址:https://www.cnblogs.com/aipeicai/p/12213322.html