zoukankan      html  css  js  c++  java
  • 队列-数组实现

    队列-数组实现

    循环数组队列核心点

    循环队列队首和队尾的一些关系(假设队首下标为front,队尾下标为rear,数组长度为MAXSIZE):

    • 队列为空:rear == front
    • 队列为满:(rear + 1) % MAXSIZE == front //(基于给队列留一个空闲位置而实现,不然和队列为空时条件重合)
    • 队列长度:(rear - front) % MAXSIZE

    代码

    public class ArrayQueue {
    
        private int maxSize;//数组的最大容量
        private int front;//队列头
        private int rear;//队列尾
        private Object[] arr;//存放数据
    
        public ArrayQueue(int maxSize) {
            this.maxSize = maxSize+1;
            this.front = 0;
            this.rear = 0;
            this.arr = new Object[maxSize+1];
        }
    
        /**
         * 检查队列是否已满
         *
         * @return
         */
        public boolean isFull() {
            return (rear + 1) % this.maxSize == this.front;
        }
    
        /**
         * 检查队列是否已空
         *
         * @return
         */
        public boolean isEmpty() {
            return this.front == this.rear;
        }
    
        /**
         * 入队操作
         *
         * @param object
         * @return
         */
        public boolean enQueue(Object object) {
    
            if (this.isFull()) return false;
    
            System.out.println(this.rear + " ");
            this.arr[this.rear] = object;
            this.rear = (this.rear + 1) % this.maxSize;
    
            return true;
        }
    
        /**
         * 出队操作
         *
         * @return
         */
        public Object outQueue() {
            if (isEmpty()) return null;
    
            Object obj = this.arr[this.front];
            this.arr[this.front] = null;
            System.out.print("font" + this.front + " ");
            this.front = (this.front + 1) % this.maxSize;
    
            return obj;
        }
    
        /**
         * 遍历队列
         */
        public void ergodicQueue() {
    
            if (isEmpty()) {
                System.out.println("队列为空");
                return;
            }
            for (Object o : this.arr) {
                System.out.print(o+"-");
            }
    
            System.out.println();
        }
    
    }
    
    
  • 相关阅读:
    Python必须知道的异常处理
    类的内置方法(用实际代码来验证)
    类的三大特性(继承, 封装, 多态)
    面向对象编程代码详解(依赖关系,关联关系,组合关系)
    函数(匿名函数,嵌套函数,高阶函数,装饰器)
    常用模块
    对磁盘文件的操作(文件处理)
    字符编码
    常用数据类型
    编程介绍
  • 原文地址:https://www.cnblogs.com/huangshen/p/13221880.html
Copyright © 2011-2022 走看看