数据结构学习心得——顺序队和链队

秒速五厘米 2022-06-09 06:19 343阅读 0赞

队列的定义

和栈相反队列是一种先进先出的线性表。它只允许在表的一端进行插入,而在另一端删除元素。这和我们日常生活中的排队是一致的,最早进入队列的元素最早离开。在队列中,允许插入的一端叫做队尾,允许删除的一端叫做对头。

顺序队和链队

顺序队列是队列的顺序存储结构,顺序队列实际上是运算受限的顺序表。和顺序表一样,顺序队列用一个向量空间来存放当前队列中的元素。由于队列的队头和队尾的位置是变化的,设置两个指针front和rear分别指示队头元素和队尾元素在向量空间中的位置,它们的初值在队列初始化时均应设置为0。

这里写图片描述

用链表表示的队列简称为链队,一个链队显然需要两个分别只是对头和队尾的指针才能唯一确定。

这里写图片描述

顺序队和链队的代码实现

这里注意顺序队我实现的是循环队,注意循环队列的队空和队满的判断上的不同。

  1. #include <iostream>
  2. using namespace std;
  3. #define maxSize 20//宏定义
  4. //顺序队列的定义
  5. typedef struct SqQueue
  6. {
  7. int data[maxSize];
  8. int front;
  9. int rear;
  10. }SqQueue;
  11. //队结点类型定义
  12. typedef struct QNode
  13. {
  14. int data;
  15. struct QNode *next;
  16. }QNode;
  17. //链队的定义
  18. typedef struct LiQueue
  19. {
  20. QNode *front;
  21. QNode *rear;
  22. }LiQueue;
  23. //顺序队列的初始化
  24. void initSqQueue(SqQueue &q)
  25. {
  26. q.front = q.rear = 0;
  27. }
  28. //判断顺序队列空
  29. int isSqQueueEmpty(SqQueue q)
  30. {
  31. if(q.front == q.rear)
  32. {
  33. return 1;
  34. }
  35. else
  36. {
  37. return 0;
  38. }
  39. }
  40. //顺序队列入队
  41. int enSqQueue(SqQueue &q,int x)
  42. {
  43. if((q.rear+1)%maxSize==q.front)
  44. {
  45. return 0;
  46. }
  47. else
  48. {
  49. q.rear = (q.rear + 1)%maxSize;
  50. q.data[q.rear] = x;
  51. return 1;
  52. }
  53. }
  54. //顺序队列出队
  55. int deSqQueue(SqQueue &q,int &x)
  56. {
  57. if(isSqQueueEmpty(q))
  58. {
  59. return 0;
  60. }
  61. else
  62. {
  63. q.front = (q.front + 1)%maxSize;
  64. x = q.data[q.front];
  65. return 1;
  66. }
  67. }
  68. //链队初始化
  69. void initQueue(LiQueue *&q)
  70. {
  71. q = new LiQueue;
  72. q->front=q->rear=NULL;
  73. }
  74. //判断链队为空
  75. int isQueueEmpty(LiQueue *q)
  76. {
  77. //这里注意q->front == q->rear不能判断链队为空,因为只有一个结点时也有q->front == q->rear
  78. if(q->front==NULL ||q->rear==NULL)
  79. {
  80. return 1;
  81. }
  82. else
  83. {
  84. return 0;
  85. }
  86. }
  87. //链队入队
  88. void enQueue(LiQueue *&q,int x)
  89. {
  90. QNode *p = new QNode;
  91. p->data = x;
  92. p->next =NULL;
  93. if(q->rear==NULL)
  94. {
  95. q->front = q->rear = p;
  96. }
  97. else
  98. {
  99. q->rear->next = p;
  100. q->rear = p;
  101. }
  102. }
  103. //链队出队
  104. int deQueue(LiQueue *&q,int &x)
  105. {
  106. QNode *p;
  107. if(isQueueEmpty(q))
  108. {
  109. return 0;
  110. }
  111. //同样注意q->front == q->rear的情况
  112. if(q->front == q->rear)
  113. {
  114. p = q->front;
  115. x = p->data;
  116. q->front = q->rear = NULL;
  117. delete p;
  118. return 1;
  119. }
  120. else
  121. {
  122. p = q->front;
  123. q->front = p->next;
  124. x = p->data;
  125. delete p;
  126. return 1;
  127. }
  128. }
  129. int main()
  130. {
  131. cout << "Hello world!" << endl;
  132. return 0;
  133. }

发表评论

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

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

相关阅读