当前位置:   article > 正文

数据结构之队列的基本实现(代码)_数据结构链队列实验代码

数据结构链队列实验代码
  1. /*基本队列的实现*/
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<assert.h>
  5. #include<malloc.h>
  6. #include<stdbool.h>
  7. //通过链表实现就要定义一个链表
  8. typedef struct ListNode
  9. {
  10. struct ListNode* next;
  11. int val;
  12. }ListNode;
  13. //定义两个节点指针 也可以解决使用二级指针的方法
  14. typedef struct queue
  15. {
  16. ListNode* head;
  17. ListNode* tail;
  18. }queue;
  19. //接口
  20. //初始化栈接口
  21. void QueueInit(queue*q)
  22. {
  23. q->head = q->tail = NULL;
  24. }
  25. //销毁栈接口
  26. void QueueDestory(queue* q)
  27. {
  28. assert(q);
  29. ListNode* cur = q->head;
  30. while (cur)
  31. {
  32. ListNode*next= cur->next;
  33. free(cur);
  34. cur = next;
  35. }
  36. q->head = q->tail = NULL;
  37. }
  38. //队尾进接口
  39. void QueuePush( queue*q,int val)
  40. {
  41. assert(q);
  42. ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
  43. if (newnode == NULL)
  44. {
  45. printf("创建节点失败!\n");
  46. exit(-1);
  47. }
  48. else
  49. {
  50. newnode->next = NULL;
  51. newnode->val = val;
  52. }
  53. if (q->tail==NULL)
  54. {
  55. q->tail = q->head = newnode;
  56. }
  57. else
  58. {
  59. q->tail->next = newnode;
  60. q->tail = newnode;
  61. }
  62. }
  63. //队头出接口
  64. void QueuePop(queue* q)
  65. {
  66. assert(q);
  67. assert(q->head);
  68. //极端情况 就是队列只有一个节点的情况 此时你的tail的空间已经被释放了但是你的tail还是指向一块地址的 所有tail会形成一个野指针
  69. //单独判断
  70. if (q->head->next==NULL)
  71. {
  72. free(q->head);
  73. q->head = q->tail = NULL;
  74. }
  75. else
  76. {
  77. ListNode* tmp = q->head->next;
  78. free(q->head);
  79. q->head = tmp;
  80. }
  81. }
  82. bool QueueEmpty(queue* q);
  83. //返回队头的接口
  84. int QueueFront(queue* q)
  85. {
  86. assert(q);
  87. if (!QueueEmpty(q))
  88. {
  89. return q->head->val;
  90. }
  91. else
  92. {
  93. return NULL;
  94. }
  95. }
  96. //返回队尾接口
  97. int QueueBack(queue* q)
  98. {
  99. assert(q);
  100. assert(q->head);
  101. return q->tail->val;
  102. }
  103. bool QueueEmpty(queue* q)
  104. {
  105. assert(q);
  106. //为空就是真
  107. return q->head == NULL;
  108. }
  109. int main()
  110. {
  111. queue q;
  112. QueueInit(&q);
  113. QueuePush(&q, 1);
  114. QueuePush(&q, 2);
  115. QueuePush(&q, 3);
  116. QueuePush(&q, 4);
  117. while (!QueueEmpty(&q))
  118. {
  119. printf("%d ", QueueFront(&q));
  120. QueuePop(&q);
  121. }
  122. printf("\n");
  123. int ret = QueueFront(&q);
  124. printf("%d ", ret);
  125. return 0;
  126. }

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

闽ICP备14008679号