队列:

只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(FirstIn First Out)。 入队列:进行插入操作的一端称为队尾(Tail/Rear)出队列:进行删除操作的一端称为队头。

循环队列:

  • 将队头和队尾以某种方式关联起来,在逻辑上达到循环一圈的目的。
  • 力扣上有原题,我是按照力扣上的题目要求写的。力扣622—设计循环队列

思路:

  1. 通过数组作为底层结构。
  2. 定义一个头指针,指向第一个元素。
  3. 定义一个尾指针,永远指向最后一个数据的下一个位置。
  4. 当要添加元素时,直接将元素插在尾指针位置,然后尾指针后移一步。
  5. 当要删除元素时,判断元素位置在头指针位置、尾位置、还是中间位置。头位置直接将头指针后移一步。尾位置将尾指针前移一步。
  6. 重要:循环队列里最奇妙的是指针走到数据终点如何让他再次从头走得问题。在这里,可以通过(尾指针下标 + 1 )% 数组长度。

实现

  1. class MyCircularQueue {
  2. //定义一个数组
  3. public int[] circleArray;
  4. //头指针
  5. public int head;
  6. //尾指针
  7. public int tail;
  8. //元素数量
  9. public int count;
  10. /** Initialize your data structure here. Set the size of the queue to be k. */
  11. public MyCircularQueue(int k) {
  12. this.circleArray = new int[k + 1];
  13. this.count = 0;
  14. this.head = 0;
  15. this.tail = 0;
  16. }
  17. /** Insert an element into the circular queue. Return true if the operation is successful. */
  18. //插入元素
  19. public boolean enQueue(int value) {
  20. if (isFull()) {
  21. //队列满,返回
  22. return false;
  23. } else {
  24. //队尾元素赋值
  25. circleArray[tail] = value;
  26. //元素数量+1
  27. count++;
  28. //队尾指针+1
  29. tail = (tail + 1) % circleArray.length;
  30. }
  31. return true;
  32. }
  33. /** Delete an element from the circular queue. Return true if the operation is successful. */
  34. //删除队头元素
  35. public boolean deQueue() {
  36. if (isEmpty()) {
  37. return false;
  38. } else {
  39. circleArray[head] = 0;
  40. head = (head + 1) % circleArray.length;
  41. count--;
  42. //circleArray[tail] = 0;
  43. //tail = (tail - 1) % circleArray.length;
  44. }
  45. return true;
  46. }
  47. /** Get the front item from the queue. */
  48. //队首获取元素
  49. public int Front() {
  50. if (isEmpty()) {
  51. return -1;
  52. } else {
  53. return circleArray[head];
  54. }
  55. }
  56. /** Get the last item from the queue. */
  57. //获取队尾元素
  58. public int Rear() {
  59. if (isEmpty()) {
  60. return -1;
  61. } else {
  62. if (tail == 0) {
  63. return circleArray[circleArray.length - 1];
  64. } else {
  65. return circleArray[tail - 1];
  66. }
  67. }
  68. }
  69. /** Checks whether the circular queue is empty or not. */
  70. public boolean isEmpty() {
  71. return head == tail;
  72. }
  73. /** Checks whether the circular queue is full or not. */
  74. public boolean isFull() {
  75. return (tail + 1) % circleArray.length == head;
  76. }
  77. //为了方便自己调试而写的打印方法
  78. public void display() {
  79. int a = head;
  80. int b = tail;
  81. while (a != b) {
  82. System.out.print(circleArray[a]+" ");
  83. a = (a + 1) % circleArray.length;
  84. }
  85. System.out.println();
  86. }
  87. }