【数据结构】循环队列的实现

末蓝、 2021-09-16 10:44 505阅读 0赞
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #include<time.h>
  5. #define TURE 1
  6. #define FALSE 0
  7. #define OK 1
  8. #define ERROR 0
  9. #define INFEASIBLE -1
  10. #define OVERFLOW -2
  11. #define MAXSIZE 100 //最大队列长度
  12. typedef int Status;
  13. typedef struct{
  14. int stuNo;
  15. char name[10];
  16. }Student;
  17. typedef struct{
  18. Student* base;//初始化的动态分配存储空间
  19. int front; //头指针,如果队列不空,指向队列的头元素
  20. int rear; //尾指针,如果队列不空,指向队列尾元素的下一个位置
  21. }SqQueue;
  22. Status InitQueue(SqQueue &Q){
  23. Q.base = (Student*)malloc(MAXSIZE*sizeof(Student));
  24. if(!Q.base) return OVERFLOW;//分配失败的情况
  25. Q.front = Q.rear =0;
  26. return OK;
  27. }
  28. int QueueLength(SqQueue Q){
  29. return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
  30. }
  31. Status EnQueue(SqQueue &Q,Student s){
  32. //插入元素s为Q的新的队尾元素
  33. if((Q.rear+1)%MAXSIZE==Q.front) return ERROR;// 队列满
  34. Q.base[Q.rear]=s;
  35. Q.rear =(Q.rear+1)%MAXSIZE;
  36. return OK;
  37. }
  38. Status DeQueue(SqQueue &Q,Student &s){
  39. //如果队列不空,则删除Q的队头元素,用e返回其值,并返回OK
  40. //如果队列为空,返回ERROR
  41. if(Q.rear==Q.front) return ERROR;
  42. s = Q.base[Q.front];
  43. Q.front = (Q.front+1)%MAXSIZE;
  44. return OK;
  45. }
  46. Status EmptyQueue(SqQueue Q){
  47. //判断队列是是否为空,如果为空,返回TURE,否则返回FALSE
  48. if(Q.front==Q.rear) return TURE;
  49. else return FALSE;
  50. }
  51. void travelQueue(SqQueue Q){
  52. //遍历打印Q中的元素
  53. int p;
  54. printf("队列中元素为:\n");
  55. for(p=Q.front;(p+1)%MAXSIZE!=Q.rear;p=(p+1)%MAXSIZE){
  56. printf("%d %s\n",Q.base[p].stuNo,Q.base[p].name);
  57. }
  58. printf("%d %s\n",Q.base[p].stuNo,Q.base[p].name);
  59. printf("\n");
  60. }
  61. int main(){
  62. SqQueue q;
  63. InitQueue(q);
  64. Student s;
  65. strcpy(s.name,"");
  66. srand(time(0));
  67. for(int i=0;i<5;i++){
  68. s.stuNo=rand()%100+1;
  69. strcat(s.name,"a");
  70. EnQueue(q,s);
  71. }
  72. travelQueue(q);
  73. printf("出队:\n");
  74. DeQueue(q,s);
  75. travelQueue(q);
  76. printf("入队:\n");
  77. s.stuNo=rand()%100+1;
  78. strcat(s.name,"a");
  79. EnQueue(q,s);
  80. travelQueue(q);
  81. return 0;
  82. }

发表评论

表情:
评论列表 (有 0 条评论,505人围观)

还没有评论,来说两句吧...

相关阅读