循环队列:

入队,出队,取队顶元素

  1 #include<stdio.h>
  2 
  3 #define OK 1
  4 #define ERROR 0
  5 #define OVERFLOW -1
  6 #define MAXSIZE 100
  7 #define TRUE 1
  8 #define FALSE 0
  9 
 10 typedef int Status;
 11 typedef int ElemType;
 12 
 13 typedef struct{
 14     ElemType data[MAXSIZE];
 15     int front,rear;
 16 }SqQueue;//循环队列类型
 17 
 18 //函数定义
 19 Status EnQueue(SqQueue &Q,ElemType e)//入队
 20 {
 21     printf("请您实现入队操作!\n");
 22 
 23     if((Q.rear+1)%MAXSIZE==Q.front)
 24         return ERROR;
 25     Q.data[Q.rear]=e;
 26     Q.rear=(Q.rear+1)%MAXSIZE;
 27 
 28     return OK;
 29 }
 30 
 31 Status DeQueue(SqQueue &Q,ElemType &e)//出队
 32 {
 33     printf("请您实现出队操作!\n");
 34 
 35     if(Q.front==Q.rear)
 36         return ERROR;
 37     e=Q.data[Q.front];
 38     Q.front=(Q.front+1)%MAXSIZE;
 39 
 40     return OK;
 41 }
 42 
 43 Status GetFront(SqQueue Q,ElemType &e)//取队头元素到e
 44 {
 45     if(Q.rear==Q.front)
 46         return OVERFLOW;
 47     e=Q.data[Q.front];
 48     return OK;
 49 }
 50 void InitQueue(SqQueue &Q)//队列初始化
 51 {
 52     Q.rear=Q.front=0;
 53 }
 54 
 55 int QEmpty(SqQueue Q)//判队空
 56 {
 57     if(Q.front==Q.rear)
 58         return TRUE;
 59     else
 60         return FALSE;
 61 }
 62 
 63 int QFull(SqQueue Q)//判队满
 64 {
 65     return ((Q.rear+1)%MAXSIZE==Q.front);
 66 }
 67 
 68 void QTravels(SqQueue Q)//遍历队列,打印队列中所有元素
 69 {
 70     int i;
 71     if(Q.rear==Q.front)
 72         printf("\n队列为空!\n");
 73     else
 74     {
 75         i=Q.front;
 76         while(i!=Q.rear)
 77         {
 78             printf("%d  ",Q.data[i]);
 79             i=(i+1)%MAXSIZE;
 80         }
 81     }
 82 }
 83 
 84 int QLength(SqQueue Q)
 85 {
 86     return (Q.rear+MAXSIZE-Q.front)%MAXSIZE;
 87 }
 88 
 89 void main()
 90 {
 91     int i;
 92     SqQueue Q1;
 93     InitQueue(Q1);
 94     for(i=0;i<5;i++)
 95     {
 96         if(EnQueue(Q1,i)==1)
 97             printf("%d入队成功!\n",i);
 98     }
 99     printf("队列遍历结果:\n");
100     QTravels(Q1);
101     int e;
102     printf("\n队列长度是:%d\n",QLength(Q1));
103     printf("\n出队一次:\n");
104     DeQueue(Q1,e);
105     printf("\n出队元素是:%d\n",e);
106     printf("\n队列长度是:%d\n",QLength(Q1));
107     printf("队列遍历结果:\n");
108     QTravels(Q1);
109     putchar('\n');
110 }

 

posted on 2016-10-17 19:18  惟愿。。。  阅读(195)  评论(0编辑  收藏  举报