当前位置:   article > 正文

队列入队出队操作

队列入队出队操作

front:对头下标

rear:队尾下标

入队:cntl->rear++

出队:cntl->front++

队满:(cntl->rear+1)%cntl->size==cntl->front

对空:cntl->rear==cntl->front

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. typedef int Datatype;
  5. //设计队列
  6. typedef struct Queue
  7. {
  8. int size;//队长
  9. Datatype *ptr;//队入口地址
  10. int front;//对头下标
  11. int rear;//对尾下标
  12. }Queue,*P_Queue;
  13. P_Queue IntiQueue(int Size)
  14. {
  15. P_Queue cntl=calloc(1,sizeof(Queue));
  16. if(cntl==NULL)
  17. {
  18. printf("申请空间失败\n");
  19. exit(0);
  20. }
  21. cntl->rear=cntl->front=0;
  22. cntl->size=Size;
  23. cntl->ptr=calloc(Size,sizeof(Datatype));
  24. return cntl;
  25. }
  26. int enQueue(P_Queue cntl,Datatype *data)
  27. {
  28. if((cntl->rear+1)%cntl->size==cntl->front)
  29. {
  30. printf("队列已经满\n");
  31. return -1;
  32. }
  33. cntl->rear++;
  34. memcpy(cntl->ptr+cntl->rear,data,sizeof(Datatype));
  35. printf("入队data:%d\n",*data);
  36. }
  37. int outQueue(P_Queue cntl,Datatype *data)
  38. {
  39. if(cntl->rear==cntl->front)
  40. {
  41. printf("队列为空\n");
  42. exit(0);
  43. }
  44. cntl->front=(cntl->front+1)%cntl->size;
  45. memcpy(data,cntl->ptr+cntl->front,sizeof(Datatype));
  46. printf("出队data:%d\n" , *data);
  47. }
  48. int main(int argc, char const *argv[])
  49. {
  50. P_Queue cntl=IntiQueue(20);
  51. int data=1;
  52. for (int i = 0; i <5; i++)
  53. {
  54. //添加数据
  55. enQueue(cntl,&data);
  56. data=data+2;
  57. }
  58. for (int i = 0; i < 8; i++)
  59. {
  60. outQueue( cntl , &data);
  61. }
  62. return 0;
  63. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/706912
推荐阅读
相关标签
  

闽ICP备14008679号