【数据结构】链式队列的实现

梦里梦外; 2021-09-16 10:44 469阅读 0赞
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #define TURE 1
  5. #define FALSE 0
  6. #define OK 1
  7. #define ERROR 0
  8. #define INFEASIBLE -1
  9. #define OVERFLOW -2
  10. typedef int Status;
  11. typedef struct{
  12. int stuNo;
  13. char name[10];
  14. }QElemType;// 定义了一个新类型,类型名为 QElemType
  15. typedef struct QNode{
  16. QElemType data;
  17. struct QNode* next; // 指向QNode类型的指针
  18. }QNode,*QueuePtr; // QueuePtr的类型为 QNode* ,即指向自己的一个指针
  19. typedef struct{
  20. QueuePtr front; //队头指针
  21. QueuePtr rear; // 队尾指针
  22. }LinkQueue;
  23. Status InitQuque(LinkQueue &Q){ // 初始化队列
  24. Q.front=Q.rear = (QueuePtr)malloc(sizeof(QNode));
  25. if(!Q.front) return OVERFLOW;//存储分配失败
  26. Q.front->next=NULL;
  27. return OK;
  28. }
  29. Status DestroyQueue(LinkQueue &Q){ //销毁队列
  30. while(Q.front){ //当 头指针不空的时候回
  31. Q.rear=Q.front->next;
  32. free(Q.front);
  33. Q.front =Q.rear;
  34. }
  35. return OK;
  36. }
  37. Status getHead(LinkQueue Q,QElemType &e){
  38. if(Q.front==Q.rear) return ERROR;
  39. e= Q.front->next->data;
  40. return OK;
  41. }
  42. Status QueueEmpty(LinkQueue Q){
  43. if(Q.front==Q.rear) return TURE;
  44. else return FALSE;
  45. }
  46. int QueueLength(LinkQueue Q){
  47. int n=0;
  48. while(Q.front!=Q.rear){
  49. Q.front= Q.front->next;
  50. n++;
  51. }
  52. return n;
  53. }
  54. Status EnQueue(LinkQueue &Q,QElemType e){ //插入元素e为队列Q的新的队尾元素
  55. QueuePtr p =(QueuePtr)malloc(sizeof(QNode));
  56. if(!p) return OVERFLOW; //存储分配失败
  57. p->data=e; p->next=NULL;
  58. Q.rear->next=p;
  59. Q.rear=p;
  60. return OK;
  61. }
  62. Status DeQueue(LinkQueue &Q, QElemType &e){
  63. if(Q.front==Q.rear) return ERROR;// 头指针和尾指针指向同一位置时,队列为空
  64. QueuePtr p = Q.front->next; //p指针指向队头元素
  65. e = p->data;
  66. Q.front->next = p->next;
  67. if(Q.rear==p) Q.rear=Q.front;//如果队头元素已经是队列的最后一个元素,让尾指针指向和头指针指向的位置
  68. free(p);
  69. return OK;
  70. }
  71. void QueueTravel(LinkQueue Q){
  72. QueuePtr p=Q.front;
  73. while(p!=Q.rear){
  74. p = p->next;
  75. printf("\n%d %s",p->data.stuNo,p->data.name);
  76. }
  77. }
  78. int main()
  79. {
  80. LinkQueue Q;
  81. InitQuque(Q);
  82. QElemType e;
  83. for(int i=0;i<3;i++){
  84. scanf("%d%s",&e.stuNo,e.name);
  85. EnQueue(Q,e);
  86. }
  87. QueueTravel(Q);
  88. printf("\nDEQueue:");
  89. DeQueue(Q,e);
  90. QueueTravel(Q);
  91. }

发表评论

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

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

相关阅读