• 【基础算法】用数组结构实现大小固定的循环队列


    【思想简述】 定义存储数组和队头、队尾指针和已经入队中元素个数,做好队满和队空判断条件。这里queueSize可以使用rear和front关系进行替换。

    队列基础类:

    1. public class queueByArray {
    2. //初识储存空间和队头、堆尾指针
    3. Integer[] arr;
    4. Integer front;
    5. Integer rear;
    6. Integer queueSize;
    7. public queueByArray(Integer initSize){
    8. if(initSize < 0){
    9. throw new IllegalArgumentException("初始化大小小于零");
    10. }
    11. arr = new Integer[initSize];
    12. front = rear = queueSize = 0;
    13. }
    14. //判断队是否为空
    15. public boolean isEmpty(){
    16. return queueSize==0 ? true : false;
    17. }
    18. //判断队是否满
    19. public boolean isFull(){
    20. return (queueSize == arr.length-1) ? true : false;
    21. }
    22. //进队
    23. public void inQueue(Integer num){
    24. //队满
    25. if(this.isFull()) {
    26. throw new IllegalArgumentException("队列已满!");
    27. }
    28. arr[rear] = num;
    29. rear = rear == arr.length-1 ? 0 : rear +1; //当队列不满,rear后移越界时,返回起点
    30. queueSize++;
    31. }
    32. //出队
    33. public Integer outQueue(){
    34. //队空
    35. if(this.isEmpty()){
    36. throw new IllegalArgumentException("队列为空!");
    37. }
    38. Integer tem = arr[front];
    39. front = front == arr.length-1 ? 0 : front+1;
    40. queueSize--;
    41. return tem;
    42. }
    43. }

    测试类:

    1. public class queueByArrayTest {
    2. public static void main(String[] args){
    3. queueByArray queue = new queueByArray(6);
    4. System.out.println(queue.isEmpty()); //true
    5. queue.inQueue(3);
    6. queue.inQueue(4);
    7. queue.inQueue(6);
    8. queue.inQueue(9);
    9. queue.inQueue(7);
    10. System.out.println(queue.isEmpty()); //false
    11. queue.inQueue(13);
    12. try {
    13. queue.inQueue(14); //队满
    14. }catch (Exception e){
    15. System.out.println(e);
    16. }
    17. while(!queue.isEmpty()){
    18. System.out.println(queue.outQueue()); //3,4,6,9,7
    19. }
    20. try {
    21. System.out.println(queue.outQueue()); //"队列为空"
    22. }catch (Exception e){
    23. System.out.println(e);
    24. }
    25. queue.inQueue(15);
    26. queue.inQueue(16);
    27. queue.inQueue(17);
    28. System.out.println(queue.front); //该处属性应该封装,当前为测试
    29. System.out.println(queue.rear); //该处属性应该封装
    30. }
    31. }

  • 相关阅读:
    基于JAVA口腔医院网站计算机毕业设计源码+系统+mysql数据库+lw文档+部署
    C++11详解
    如何手动获取spring/springboot中的IOC容器(全局上下文对象)?
    【ACG】博主在专栏更新内容后,及时通知关注他的用户去阅读
    Element-ui 表格&表单
    团建游戏大全
    中外企业文化杂志中外企业文化杂志社中外企业文化编辑部2022年第5期目录
    Python实现“黑猫投诉平台,舆论监控系统”
    ZCC5429 异步升压芯片
    GBase 8a MPP集群规划
  • 原文地址:https://blog.csdn.net/ckq707718837/article/details/125632802