数据结构 队列的基本操作

矫情吗;* 2022-09-19 01:30 278阅读 0赞
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define OK 1
  4. #define ERROR 0
  5. #define OVERFLOW -2
  6. typedef int QElemType;
  7. typedef struct QNode
  8. {
  9. QElemType data;
  10. struct QNode *next;
  11. }QNode, *QueuePtr;
  12. typedef struct
  13. {
  14. QueuePtr front; /*Q.front相当于单链表的头结点,即Q.front->next是第一个数据*/
  15. QueuePtr rear; /*Q.rear指向最后一个数据,,即Q.rear->next = NULL*/
  16. }LinkQueue;
  17. int InitQueue(LinkQueue &Q)
  18. {
  19. Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
  20. if (!Q.front)
  21. {
  22. exit(OVERFLOW);
  23. }
  24. Q.front ->next = NULL;
  25. return OK;
  26. }
  27. int EnQueue(LinkQueue &Q, QElemType e)
  28. {
  29. QueuePtr p;
  30. p = (QueuePtr)malloc(sizeof(QNode));
  31. if (!p)
  32. {
  33. exit(OVERFLOW);
  34. }
  35. p->data = e;
  36. p->next = NULL;
  37. Q.rear ->next = p;/*插入第一个节点时,也是Q.front->next = p;*/
  38. Q.rear = p;/*队尾始终指向最后一个元素,即Q.rear->next = NULL*/
  39. return OK;
  40. }
  41. int DeQueue(LinkQueue &Q, QElemType &e)
  42. {
  43. QueuePtr p;
  44. if (Q.front == Q.rear)
  45. {
  46. return ERROR;
  47. }
  48. p = Q.front->next;
  49. e = p->data;
  50. Q.front->next = p->next;
  51. if (Q.rear == p )
  52. {
  53. Q.rear = Q.front ;
  54. }
  55. free(p);
  56. return OK;
  57. }
  58. int DestroyQueue(LinkQueue &Q)
  59. {
  60. while (Q.front)
  61. {
  62. Q.rear = Q.front->next ;
  63. free(Q.front);
  64. Q.front = Q.rear;
  65. }
  66. return OK;
  67. }
  68. int isQueue_Empty(LinkQueue Q)
  69. {
  70. if (Q.front == Q.rear)
  71. {
  72. return 1;
  73. }
  74. return 0;
  75. }
  76. void Print_Queue(LinkQueue Q)
  77. {
  78. if (isQueue_Empty(Q))
  79. {
  80. return;
  81. }
  82. while (Q.front != Q.rear)
  83. {
  84. printf("%d ",Q.front->next->data);
  85. Q.front = Q.front->next;
  86. }
  87. printf("\n");
  88. }
  89. int main()
  90. {
  91. int i,n,e;
  92. LinkQueue Q;
  93. scanf("%d",&n);
  94. InitQueue(Q);
  95. for (i=0; i<n; i++)
  96. {
  97. scanf("%d",&e);
  98. EnQueue(Q, e);
  99. }
  100. Print_Queue(Q);
  101. DeQueue(Q,e);
  102. Print_Queue(Q);
  103. EnQueue(Q, 100);
  104. Print_Queue(Q);
  105. EnQueue(Q, 200);
  106. Print_Queue(Q);
  107. DestroyQueue(Q);
  108. return 0;
  109. }

发表评论

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

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

相关阅读

    相关 基本操作 数据结构

    队列(queue)也是线性表的一种特殊情况,其所有的插入均限定在表的一端进行,而所有的删除则限定在表的另一端进行。允许插入的一端称队尾(rear),允许删除的一端称队头(fro

    相关 数据结构系列-基本操作

    队列(Queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。允许插入的端是队尾,允许删除的端是队头。 所以说队列是一个先进先出的线性表,相应的也有顺序存储和