概括

  • 始终在一端插入数据,另一端删除数据
  • 先进先出(FIFO,First Input First Output)
  • 插入和删除时间复杂度O(1)

image.png

循环队列

通过 双指针 + 数组 实现循环队列

  1. public class QueueDemo {
  2. public static void main(String[] args) {
  3. MyQueue myQueue = new MyQueue();
  4. myQueue.enQueue(3);
  5. myQueue.enQueue(5);
  6. myQueue.enQueue(6);
  7. myQueue.enQueue(8);
  8. myQueue.enQueue(1);
  9. myQueue.deQueue();
  10. myQueue.deQueue();
  11. myQueue.deQueue();
  12. myQueue.enQueue(2);
  13. myQueue.enQueue(4);
  14. myQueue.enQueue(9);
  15. myQueue.print();
  16. }
  17. public static class MyQueue {
  18. private final int[] arr = new int[10];
  19. private int front;
  20. private int rear;
  21. public void enQueue(int element) {
  22. if ((rear + 1) % arr.length == front) {
  23. throw new RuntimeException("队列已满!");
  24. }
  25. arr[rear] = element;
  26. rear = (rear + 1) % arr.length;
  27. }
  28. public int deQueue() {
  29. if (rear == front) {
  30. throw new RuntimeException("队列已空!");
  31. }
  32. int remove = arr[front];
  33. front = (front + 1) % arr.length;
  34. return remove;
  35. }
  36. public void print() {
  37. for (int i = front; i != rear; i = (i + 1) % arr.length) {
  38. System.out.println(arr[i]);
  39. }
  40. }
  41. }
  42. }