队列是一种FIFO(先进先出)的数据结构,其插入新元素被称为入队,删除被称为出队,每次删除的都是最先入队的元素,即第一个元素。
队列 - 图1

实现

采用 List 数组来存储数据,指针 p_start 来指示队列的第一个元素位置。随着 p_start 的移动,越来越多的空间被浪费。

  • isEmpty :指针位置大于等于数组的大小
  • front :队列的第一个元素
  • enQueue :添加数据
  • deQueue :如果队列为空,则返回false,否则将 p_start +1,返回True ```java import java.util.ArrayList; import java.util.List;

public class MyQueue { private List data; private int p_start;

  1. /**
  2. * @return whether queue is empty
  3. */
  4. public boolean isEmpty() {
  5. return p_start >= data.size();
  6. }
  7. /**
  8. * @return the front item from the queue
  9. */
  10. public int front() {
  11. return data.get(p_start);
  12. }
  13. /**
  14. * insert an element into the queue
  15. *
  16. * @param x
  17. * @return whether insert successfully
  18. */
  19. public boolean enQueue(int x) {
  20. data.add(x);
  21. return true;
  22. }
  23. /**
  24. * delete the first item from the queue
  25. *
  26. * @return true if the operation is successful
  27. */
  28. public boolean deQueue() {
  29. if (!isEmpty()) {
  30. p_start++;
  31. return true;
  32. } else
  33. return false;
  34. }
  35. public MyQueue() {
  36. data = new ArrayList<>();
  37. p_start = 0;
  38. }

}

  1. <a name="wFWiR"></a>
  2. # 循环队列
  3. 对于上述的队列来说,空间被大大浪费了,**循环队列**采用固定的长度数组和两个指针来指示起始位置。
  4. ```java
  5. public class MyCircularQueue {
  6. private int[] data;
  7. private int head;
  8. private int tail;
  9. private int size;
  10. /**
  11. * Initialize your data structure here. Set the size of the queue to be k.
  12. */
  13. public MyCircularQueue(int k) {
  14. data = new int[k];
  15. head = tail = -1;
  16. size = k;
  17. }
  18. /**
  19. * Insert an element into the circular queue. Return true if the operation is successful.
  20. */
  21. public boolean enQueue(int value) {
  22. if (isFull())
  23. return false;
  24. if (isEmpty())
  25. head = 0;
  26. tail = (tail + 1) % size;
  27. data[tail] = value;
  28. return true;
  29. }
  30. /**
  31. * Delete an element from the circular queue. Return true if the operation is successful.
  32. */
  33. public boolean deQueue() {
  34. if (isEmpty())
  35. return false;
  36. if (head == tail) {
  37. head = tail = -1;
  38. return true;
  39. }
  40. head = (head + 1) % size;
  41. return true;
  42. }
  43. /**
  44. * Get the front item from the queue.
  45. */
  46. public int Front() {
  47. if (isEmpty())
  48. return -1;
  49. return data[head];
  50. }
  51. /**
  52. * Get the last item from the queue.
  53. */
  54. public int Rear() {
  55. if (isEmpty())
  56. return -1;
  57. return data[tail];
  58. }
  59. /**
  60. * Checks whether the circular queue is empty or not.
  61. */
  62. public boolean isEmpty() {
  63. return head == -1;
  64. }
  65. /**
  66. * Checks whether the circular queue is full or not.
  67. */
  68. public boolean isFull() {
  69. return ((tail + 1) % size) == head;
  70. }
  71. }

参考

  1. leetcode 数据结构——队列