一点一点

队列-数组实现

队列-数组实现

循环数组队列核心点

循环队列队首和队尾的一些关系(假设队首下标为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();
    }

}

posted @ 2020-07-01 22:09  6风筝9  阅读(111)  评论(0编辑  收藏  举报