第七周 项目3

来源:互联网 发布:360手机文件夹加密软件 编辑:程序博客网 时间:2024/05/12 14:14
  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3. #include "sqqueue.h"  
  4.   
  5. int main()  
  6. {  
  7.     ElemType a,x;  
  8.     SqQueue *qu;    //定义队列  
  9.     InitQueue(qu);  //队列初始化  
  10.     while (1)  
  11.     {  
  12.         printf("输入a值(输入正数进队,负数出队,0结束):");  
  13.         scanf("%d", &a);  
  14.         if (a>0)  
  15.         {  
  16.             if (!enQueue(qu,a))  
  17.                 printf("  队列满,不能入队\n");  
  18.         }  
  19.         else if (a<0)  
  20.         {  
  21.             if (!deQueue(qu, x))  
  22.                 printf("  队列空,不能出队\n");  
  23.         }  
  24.         else  
  25.             break;  
  26.     }  
  27.     return 0;  
  28. }  
[csharp] view plain copy
  1. <span style="color:#ff0000;">sqqueue.cpp</span>  
[csharp] view plain copy
  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3. #include "sqqueue.h"  
  4.   
  5. void InitQueue(SqQueue *&q)  //初始化顺序环形队列  
  6. {  
  7.     q=(SqQueue *)malloc (sizeof(SqQueue));  
  8.     q->front=q->rear=0;  
  9. }  
  10. void DestroyQueue(SqQueue *&q) //销毁顺序环形队列  
  11. {  
  12.     free(q);  
  13. }  
  14. bool QueueEmpty(SqQueue *q)  //判断顺序环形队列是否为空  
  15. {  
  16.     return(q->front==q->rear);  
  17. }  
  18.   
  19.   
  20. int QueueLength(SqQueue *q)   //返回队列中元素个数,也称队列长度  
  21. {  
  22.     return (q->rear-q->front+MaxSize)%MaxSize;  
  23. }  
  24.   
  25. bool enQueue(SqQueue *&q,ElemType e)   //进队  
  26. {  
  27.     if ((q->rear+1)%MaxSize==q->front)  //队满上溢出  
  28.         return false;  
  29.     q->rear=(q->rear+1)%MaxSize;  
  30.     q->data[q->rear]=e;  
  31.     return true;  
  32. }  
  33. bool deQueue(SqQueue *&q,ElemType &e)  //出队  
  34. {  
  35.     if (q->front==q->rear)      //队空下溢出  
  36.         return false;  
  37.     q->front=(q->front+1)%MaxSize;  
  38.     e=q->data[q->front];  
  39.     return true;  
  40. }  
[csharp] view plain copy
  1. <span style="color:#ff0000;">sqqueue.h</span>  

[csharp] view plain copy
  1. #ifndef SQQUEUE_H_INCLUDED  
  2. #define SQQUEUE_H_INCLUDED  
  3.  
  4. #define MaxSize 5  
  5. typedef char ElemType;  
  6. typedef struct  
  7. {  
  8.     ElemType data[MaxSize];  
  9.     int front,rear;     /*队首和队尾指针*/  
  10. } SqQueue;  
  11.   
  12.   
  13. void InitQueue(SqQueue *&q);  //初始化顺序环形队列  
  14. void DestroyQueue(SqQueue *&q); //销毁顺序环形队列  
  15. bool QueueEmpty(SqQueue *q);  //判断顺序环形队列是否为空  
  16. int QueueLength(SqQueue *q);   //返回队列中元素个数,也称队列长度  
  17. bool enQueue(SqQueue *&q,ElemType e);   //进队  
  18. bool deQueue(SqQueue *&q,ElemType &e);  //出队  
  19.  
原创粉丝点击