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