image.png
数组队列出队的时间复杂度为 O(n) 循环队列出队为 O(1)(均摊时间复杂度,因为缩容时时间复杂度还是 O(n))
数组队列在删除队首元素时后面的元素要往前移动,比较耗时,循环队列使用 front 指针后移无需移动后面元素,
出队腾出的空间会在最后位置填充时利用。

tail == front 时队列为空,tail 指针要保证指向空间没有元素

实现

  1. public class LoopQueue<E> implements Queue<E> {
  2. private E[] data;
  3. private int front, tail;
  4. private int size;
  5. public LoopQueue(int capacity) {
  6. data = (E[])new Object[capacity + 1];
  7. front = 0;
  8. tail = 0;
  9. size = 0;
  10. }
  11. public LoopQueue() {
  12. this(10);
  13. }
  14. public int getCapacity() {
  15. return data.length - 1;
  16. }
  17. @Override
  18. public int getSize() {
  19. return size;
  20. }
  21. @Override
  22. public boolean isEmpty() {
  23. return front == tail;
  24. }
  25. @Override
  26. public void enqueue(E e) {
  27. if ((tail + 1) % data.length == front) {
  28. resize(getCapacity() * 2);
  29. }
  30. data[tail] = e;
  31. tail = (tail + 1) % data.length;
  32. size ++;
  33. }
  34. private void resize(int newCapacity) {
  35. E[] newData = (E[])new Object[newCapacity + 1];
  36. for (int i = 0; i < size; i ++) {
  37. newData[i] = data[(i + front) % data.length];
  38. }
  39. data = newData;
  40. front = 0;
  41. tail = size;
  42. }
  43. @Override
  44. public E dequeue() {
  45. if (isEmpty()) {
  46. throw new NoSuchElementException("Cannot dequeue from an empty queue!");
  47. }
  48. E ret = data[front];
  49. data[front] = null;
  50. front = (front + 1) % data.length;
  51. size --;
  52. // 缩容
  53. if (size == getCapacity() / 4 && getCapacity() / 2 != 0){
  54. resize(getCapacity() / 2);
  55. }
  56. return ret;
  57. }
  58. @Override
  59. public E getFront() {
  60. if (isEmpty()) {
  61. throw new NoSuchElementException("Cannot dequeue from an empty queue!");
  62. }
  63. return data[front];
  64. }
  65. @Override
  66. public String toString() {
  67. StringBuilder res = new StringBuilder();
  68. res.append(String.format("Queue: size = %d, capacity = %d\n", size, getCapacity()));
  69. res.append("front: [");
  70. for (int i = front; i != tail; i = (i + 1) % data.length) {
  71. res.append(data[i]);
  72. if ((i + 1) % data.length != tail) {
  73. res.append(", ");
  74. }
  75. }
  76. res.append("] tail");
  77. return res.toString();
  78. }
  79. public static void main(String[] args) {
  80. LoopQueue<Integer> queue = new LoopQueue<>();
  81. for (int i = 0; i < 10; i++) {
  82. queue.enqueue(i);
  83. System.out.println(queue);
  84. if (i % 3 == 2) {
  85. queue.dequeue();
  86. System.out.println(queue);
  87. }
  88. }
  89. }
  90. }