第七周项目三

来源:互联网 发布:国学小达人网络挑战赛 编辑:程序博客网 时间:2024/06/01 18:44
/*
Copyright (c++) 2017,烟台大学计算机与控制工程学院
文件名称:jcy
作 者:贾存钰
完成日期:2017年10月19日
问题描述:设从键盘输入一整数序列a1,a2,…an,试编程实现:当ai>0时,ai进队,当ai<0时,将队首元素出队,
当ai=0时,表示输入结束。要求将队列处理成环形队列,使用算法库中定义的数据类型及算法,
程序中只包括一个函数(main函数),入队和出队等操作直接写在main函数中即可。当进队出队异常(如队满)时,
要打印出错信息。
输入描述:一整数序列
输出描述:

*/

[cpp] view plain copy
  1. #ifndef LIQUEUE_H_INCLUDED  
  2. #define LIQUEUE_H_INCLUDED  
  3.   
  4. typedef int ElemType;  
  5. typedef struct qnode  
  6. {  
  7.     ElemType data;  
  8.     struct qnode *next;  
  9. } QNode;        //链队数据结点类型定义  
  10.   
  11. typedef struct  
  12. {  
  13.     QNode *front;  
  14.     QNode *rear;  
  15. } LiQueue;          //链队类型定义  
  16. void InitQueue(LiQueue *&q);  //初始化链队  
  17. void DestroyQueue(LiQueue *&q);  //销毁链队  
  18. bool QueueEmpty(LiQueue *q);  //判断链队是否为空  
  19. int QueueLength(LiQueue *q);  //返回队列中数据元素个数  
  20. void enQueue(LiQueue *&q,ElemType e);  //入队  
  21. bool deQueue(LiQueue *&q,ElemType &e);   //出队  
  22.   
  23. #endif // LIQUEUE_H_INCLUDED  

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3. #include "liqueue.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. }  
[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3. #include "liqueue.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. }  

原创粉丝点击