思路

用两个指针pushi和polli指向当前要弹出和插入的位置。
size表示当前数组的容量,limit表示数组的最大容量。有这两个变量可以简化代码的编写。

  1. public static class MyQueue {
  2. private int[] arr;
  3. private int pushi;// end
  4. private int polli;// begin
  5. private int size;
  6. private final int limit;
  7. public MyQueue(int limit) {
  8. arr = new int[limit];
  9. pushi = 0;
  10. polli = 0;
  11. size = 0;
  12. this.limit = limit;
  13. }
  14. public void push(int value) {
  15. if (size == limit) {
  16. throw new RuntimeException("队列满了,不能再加了");
  17. }
  18. size++;
  19. arr[pushi] = value;
  20. pushi = nextIndex(pushi);
  21. }
  22. public int pop() {
  23. if (size == 0) {
  24. throw new RuntimeException("队列空了,不能再拿了");
  25. }
  26. size--;
  27. int ans = arr[polli];
  28. polli = nextIndex(polli);
  29. return ans;
  30. }
  31. public boolean isEmpty() {
  32. return size == 0;
  33. }
  34. // 如果现在的下标是i,返回下一个位置
  35. private int nextIndex(int i) {
  36. return i < limit - 1 ? i + 1 : 0;
  37. }
  38. }