云中烛火

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

循环队列的基本操作
  

  1 #include<string.h>
  2 #include<ctype.h>
  3 #include<malloc.h>
  4 #include<limits.h>
  5 #include<stdio.h>
  6 #include<stdlib.h>
  7 #include<math.h>
  8 
  9 #define TRUE 1
 10 #define FALSE 0
 11 #define OK 1
 12 #define ERROR 0
 13 #define INFEASIBLE -1
 14 
 15 typedef int Status;
 16 typedef int Boolean;
 17 typedef int QElemType;
 18 
 19 #define MAXQSIZE 100
 20 typedef struct
 21 {
 22     QElemType *base;
 23     int front;
 24     int rear;
 25 }SqQueue;
 26 
 27 Status InitQueue(SqQueue *Q)
 28 {
 29     //构造一个空队列Q
 30     (*Q).base=(QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
 31     if(!(*Q).base)
 32         exit(OVERFLOW);
 33     (*Q).front=(*Q).rear=0;
 34     return OK;
 35 }
 36 
 37 Status DestroyQueue(SqQueue *Q)
 38 {
 39     //销毁队列Q
 40     if((*Q).base)
 41         free((*Q).base);
 42     (*Q).base=NULL;
 43     (*Q).front=(*Q).rear=0;
 44     return OK;
 45 }
 46 
 47 Status ClearQueue(SqQueue *Q)
 48 {//将队列Q清为空队列
 49     (*Q).front=(*Q).rear=0;
 50     return OK;
 51 }
 52 
 53 Status QueueEmpty(SqQueue Q)
 54 {
 55     //若队列Q为空队列,则返回TRUE,否则返回FALSE
 56     if(Q.front==Q.rear)
 57         return TRUE;
 58     else
 59         return FALSE;
 60 }
 61 
 62 int QueueLength(SqQueue Q)
 63 {//返回队列Q的元素个数,即队列的长度
 64         return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
 65 }
 66 
 67 Status GetHead(SqQueue Q,QElemType *e)
 68 {//若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR
 69     if(Q.front==Q.rear)
 70         return ERROR;
 71     *e=*(Q.base+Q.front);
 72     return OK;
 73 }
 74 
 75 Status EnQueue(SqQueue *Q,QElemType e)
 76 {
 77     //插入元素e为Q的队尾素
 78     if(((*Q).rear+1)%MAXQSIZE==(*Q).front)
 79         return ERROR;
 80     (*Q).base[(*Q).rear]=e;
 81     (*Q).rear=((*Q).rear+1)%MAXQSIZE;
 82     return OK;
 83 }
 84 
 85 Status DeQueue(SqQueue *Q,QElemType *e)
 86 {
 87     //若队列不空,则删除Q的队列头元素,用e返回,并返回OK,否则返回ERROR
 88     if((*Q).front==(*Q).rear)//队列空
 89         return ERROR;
 90     *e=(*Q).base[(*Q).front];
 91     (*Q).front=((*Q).front+1)%MAXQSIZE;
 92     return OK;
 93 }
 94 
 95 Status QueueTraverse(SqQueue Q,void(*vi)(QElemType))
 96 {
 97     //对队列的队头到队尾依次对队列Q中的元素调用函数vi(),一旦vi()失败,则操作失败
 98     int i;
 99     i=Q.front;
100     while(i!=Q.rear)
101     {
102         vi(*(Q.base+i));
103         i=(i+1)%MAXQSIZE;
104     }
105     printf("\n");
106     return OK;
107 }

 

posted on 2013-11-17 13:23  云中烛火  阅读(125)  评论(0)    收藏  举报