下面的程序中假设:

    队首指针指示在当前队首元素的位置,队尾指针在队尾元素+1的位置指示。

 

 
  
  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3.  
  4.    
  5.  
  6. #define MAXSIZE 5  
  7. typedef char ElemType;  
  8.  
  9. typedef struct 
  10. {  
  11.  ElemType *base;  
  12.  int front;  
  13.  int rear;  
  14. }SqQueue;  
  15.  
  16.  
  17. void Clear(SqQueue *s)  
  18. {  
  19.  free(s);  
  20. }  
  21.  
  22.  
  23. void InitQueue(SqQueue *s)  
  24. {  
  25.  s->base = (ElemType *)malloc(MAXSIZE * sizeof(ElemType));  
  26.  if (!s->base)  
  27.  {  
  28.   printf("error\n");  
  29.   return;  
  30.  }  
  31.  s->front = 0;  
  32.  //首、尾指针初始化  
  33.  s->rear = s->front;  
  34. }  
  35.  
  36.  
  37. int EmptyQueue(SqQueue *s)  
  38. {  
  39.  return(s->front == s->rear);  
  40. }  
  41.  
  42.  
  43. int QueueLength(SqQueue *s)  
  44. {  
  45.  return (s->rear - s->front + MAXSIZE) % MAXSIZE;  
  46. }  
  47.  
  48.  
  49. int EnQueue(SqQueue *s,ElemType e)  
  50. {  
  51.  if ((s->rear +1) % MAXSIZE == s->front)  
  52.  {  
  53.   return 0;  
  54.  }  
  55.  s->base[s->rear] = e;  
  56.  s->rear = (s->rear + 1) % MAXSIZE;  
  57.  return 1;  
  58. }  
  59.  
  60.  
  61. int DeQueue(SqQueue *s,ElemType *e)  
  62. {  
  63.  if (s->front == s->rear)  
  64.  {  
  65.   return 0;  
  66.  }  
  67.  *e = s->base[s->front];  
  68.  s->front = (s->front + 1) % MAXSIZE;  
  69.  return 1;  
  70. }  
  71.  
  72.  
  73. void main()  
  74. {  
  75.  ElemType e;  
  76.  SqQueue *s;  
  77.  s = (SqQueue *)malloc(sizeof(SqQueue));  
  78.  InitQueue(s);  
  79.    
  80.  if (EnQueue(s,'a') == 0)  
  81.  {  
  82.   printf("队满,不能进队!");  
  83.  }  
  84.  if (EnQueue(s,'b') == 0)  
  85.  {  
  86.   printf("队满,不能进队!");  
  87.  }  
  88.  if (EnQueue(s,'c') == 0)  
  89.  {  
  90.   printf("队满,不能进队!");  
  91.  }  
  92.  printf("队列为:%s\n",(EmptyQueue(s)?"空":"非空"));  
  93.    
  94.  if (DeQueue(s,&e) == 0)  
  95.  {  
  96.   printf("队空,不能出队!\n");  
  97.  }  
  98.  else 
  99.  {  
  100.   printf("出队一个元素:% c\n", e);  
  101.  }  
  102.  
  103.  printf("队列的元素个数为:%d\n",QueueLength(s));  
  104.  
  105.  if (EnQueue(s,'d') == 0)  
  106.  {  
  107.   printf("队满,不能进队!\n");  
  108.  }  
  109.  if (EnQueue(s,'e') == 0)  
  110.  {  
  111.   printf("队满,不能进队!\n");  
  112.  }  
  113.  if (EnQueue(s,'f') == 0)  
  114.  {  
  115.   printf("队满,不能进队!\n");  
  116.  }  
  117.  
  118.  printf("队列的元素个数为:%d\n",QueueLength(s));  
  119.  
  120.  while(!EmptyQueue(s))  
  121.  {  
  122.   DeQueue(s,&e);  
  123.   printf("%c",e);  
  124.  }  
  125.  
  126.  printf("\n");  
  127.  printf("释放队列...\n");  
  128.  Clear(s);  
  129.  
  130.  while(!EmptyQueue(s))  
  131.  {  
  132.   DeQueue(s,&e);  
  133.   printf("%c",e);  
  134.  }  
  135.  
  136.  printf("释放队列成功\n");  
  137. }  
  138.