• 【数据结构与算法 | 基础篇】环形数组模拟队列


    1. 前言

    上文我们用环形单向链表实现了队列.接下来我们用环形数组来模拟队列.并实现了isFull(),isEmpty()等方法.

    2. 环形数组模拟队列

    (1). Queue接口 : 

    1. public interface Queue {
    2. //向队伍插入值, 插入成功返回true, 否则返回false
    3. boolean offer(E value);
    4. //对队头获取值, 但不移除
    5. E poll();
    6. //从队头获取值, 并移除队头
    7. E peek();
    8. //判断队伍是否为空
    9. boolean isEmpty();
    10. //判断队列是否已满
    11. boolean isFull();
    12. }

    (2). 环形数组模拟队列

    1. public class ArrayQueue implements Queue, Iterable{
    2. //数组的容量
    3. private int capacity;
    4. //环形数组
    5. private E[] queue;
    6. //队头
    7. private int head = 0;
    8. //队尾
    9. private int tail = 0;
    10. public ArrayQueue() {
    11. capacity = 10;
    12. }
    13. public ArrayQueue(int capacity) {
    14. this.capacity = capacity;
    15. //数组capacity个位置存储数据, 剩下一个位置用来区分队伍是满了还是空了的情况
    16. queue = (E[]) new Object[capacity + 1];
    17. }
    18. @Override
    19. public boolean offer(E value) {
    20. //如果队伍已经满了, 那么添加元素失败
    21. if(isFull()) {
    22. return false;
    23. }
    24. queue[tail] = value;
    25. tail = (tail + 1) % queue.length;
    26. return true;
    27. }
    28. @Override
    29. public E poll() {
    30. //如果队列为空, 那么返回null
    31. if(isEmpty()) {
    32. return null;
    33. }
    34. return queue[head];
    35. }
    36. @Override
    37. public E peek() {
    38. //如果队列为空, 那么返回null
    39. E value = queue[head];
    40. head = (head + 1) % queue.length;
    41. return value;
    42. }
    43. @Override
    44. public boolean isEmpty() {
    45. return head == tail;
    46. }
    47. @Override
    48. public boolean isFull() {
    49. //数组的长度queue.length并不等于数组的容量capacity
    50. return (tail+1) % queue.length == head;
    51. }
    52. @Override
    53. public Iterator iterator() {
    54. return new Iterator() {
    55. int p = head;
    56. @Override
    57. public boolean hasNext() {
    58. return p != tail;
    59. }
    60. @Override
    61. public E next() {
    62. E value = queue[p];
    63. p++;
    64. return value;
    65. }
    66. };
    67. }
    68. }

    3. 单元测试

    1. public class ArrayQueueTest {
    2. @Test
    3. public void test() {
    4. ArrayQueue queue = new ArrayQueue<>(5);
    5. queue.offer(1);
    6. queue.offer(2);
    7. queue.offer(3);
    8. queue.offer(4);
    9. queue.offer(5);
    10. // for (Integer element : queue) {
    11. // System.out.print(element);
    12. // }
    13. //12345
    14. System.out.println(queue.poll());
    15. //1
    16. System.out.println(queue.peek());
    17. //1
    18. System.out.println(queue.poll());
    19. //2
    20. }
    21. }
  • 相关阅读:
    排序算法的总结
    2022年武汉安全员ABC考试难吗?需要参加培训吗?甘建二
    Redis哨兵机制原理
    【笔试题】【day16】
    XC5VLX30T-2FF323I Virtex-5 LXT FPGA IC 产品参数
    内存ECC高级纠错算法有哪些?
    记录一些个人编写java工具类方法(持续更新)
    经典背包系列问题
    阿里云认证 | 2023年ACP认证考试大揭秘
    虚函数表与动态绑定
  • 原文地址:https://blog.csdn.net/2301_80912559/article/details/139031779