基于数组实现环形队列

package com.tomdd.v2.queue;

/**
 *
 * <pre>
 * <h1>基于数组实现环形队列</h1>
 *    在Java中,基于数组实现环形队列是一种常见的数据结构实现方式,
 *    它利用固定长度的数组模拟循环队列的行为,
 *    以克服普通数组实现队列时可能出现的空间浪费问题。
 *    下面是一个完整的Java类实现,
 *    包括必要的属性、构造方法、入队(enqueue)、出队(dequeue)、
 *    判断队列是否为空或满、获取队列大小等核心方法
 *
 *<h2>重点:</h2>
 *     使用取模算法,移动指针,实现环形队列的逻辑
 *<h2>思路分析:</h2>
 *    (1)构造方法:根据给定的capacity创建一个指定大小的数组,并初始化front和rear指针为0<br/>
 *    (2)isEmpty:检查front和rear是否相等,相等表示队列为空。<br/>
 *    (3) isFull:计算(rear + 1) % capacity是否等于front。如果相等,<br/>
 *        说明队尾元素的下一个位置就是队首,即队列已满。(环形队列预留一个位置)<br/>
 *    (4)size:由于是环形队列,front和rear可能会因为队列元素的进出而形成“跨越”,<br/>
 *       即rear小于front。此时,队列的实际大小需要加上数组的剩余空间(rear + capacity - front)。<br/>
 *       如果不跨越,则直接计算rear - front<br/>
 *    (5)enqueue:在队尾插入元素。首先检查队列是否已满,未满则将元素放入queue[rear]位置,<br/>
 *        并更新rear指针(取模确保它始终在数组范围内循环移动)rear = (rear + 1) % capacity;。<br/>
 *    (6)dequeue:从队首移除并返回元素。同样先检查队列是否为空,<br/>
 *       非空则取出queue[front]作为结果,将其设为null(可选,有助于垃圾回收),<br/>
 *       然后更新front指针:front = (front + 1) % capacity。<br/>
 *    (7) 查看队尾元素: queue[(rear - 1 + capacity) % capacity] <br/>
 *    (8) 查看头元素: queue[front]
 * </pre>
 *
 * @param <T>
 */
public class CircularArrayQueue<T> {
    // 定义队列内部存储数组以及其最大容量
    private final T[] queue;
    private final int capacity;
    // 队首指针(指向队列的第一个有效元素)
    private int front;
    // 队尾指针(指向队列最后一个有效元素的下一个位置)环形队列预留一个位置
    private int rear;

    /**
     * 构造方法,初始化指定容量的环形队列
     *
     * @param capacity 队列容量
     */
    @SuppressWarnings("unchecked")
    public CircularArrayQueue(int capacity) {
        this.capacity = capacity + 1;
        this.queue = (T[]) new Object[capacity];
        this.front = 0;
        this.rear = 0;
    }

    /**
     * 判断队列是否为空
     *
     * @return true - 为空,false - 不为空
     */
    public boolean isEmpty() {
        return front == rear;
    }

    /**
     * 判断队列是否已满
     *
     * @return true - 已满,false - 未满
     */
    public boolean isFull() {
        return (rear + 1) % capacity == front;
    }


    /**
     * 获取队列当前实际元素数量
     *
     * @return 队列大小
     */
    public int size() {
        if (rear < front) {
            return rear + capacity - front;
        } else {
            return rear - front;
        }
    }

    /**
     * 入队操作,将元素添加到队尾
     *
     * @param item 待入队元素
     * @return true - 入队成功,false - 队列已满无法入队
     */
    public boolean enqueue(T item) {
        if (!isFull()) {
            queue[rear] = item;
            rear = (rear + 1) % capacity;
            return true;
        }
        return false;
    }

    /**
     * 出队操作,移除并返回队首元素
     *
     * @return 出队元素,若队列为空则返回 null
     */
    public T dequeue() {
        if (!isEmpty()) {
            T result = queue[front];
            // 释放队首元素的引用(可选,避免对象游离)
            queue[front] = null;
            front = (front + 1) % capacity;
            return result;
        }
        return null;
    }


    /**
     * 打印队列所有元素
     */
    public void printQueue() {
        if (isEmpty()) {
            System.out.println("Queue is Empty!");
            return;
        }
        int tempFront = front;
        while (tempFront != rear) {
            System.out.print(queue[tempFront] + " ");
            tempFront = (tempFront + 1) % capacity;
        }
        System.out.println();
    }


    /**
     * 查看队尾元素
     *
     * @return 队尾元素
     */
    public T peekRear() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is Empty!");
        }
        return queue[(rear - 1 + capacity) % capacity];
    }

    /**
     * 查看头元素
     *
     * @return 查看头元素
     */
    public T peekFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is Empty!");
        }
        return queue[front];
    }


    public static void main(String[] args) {
        CircularArrayQueue<Integer> circularQueue = new CircularArrayQueue<>(5);

        circularQueue.enqueue(1);
        circularQueue.enqueue(2);
        circularQueue.enqueue(3);
        circularQueue.enqueue(4);
        circularQueue.enqueue(5);

        circularQueue.printQueue();
        System.out.println("-------------------------");
        Integer i = circularQueue.peekRear();
        System.out.println("队尾元素:" + i);
        Integer i1 = circularQueue.peekFront();
        System.out.println("头元素:"+i1);
        circularQueue.printQueue();
        System.out.println("-------------------------");
        System.out.println(circularQueue.dequeue()); // 输出:1
        System.out.println(circularQueue.size()); // 输出:2

    }


}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ 的环形队列是一种特殊的队列结构,它可以避免队列的内存空间浪费,同时提高队列的性能。环形队列通常使用数组或者链表来实现,本文将介绍基于数组实现环形队列。 1. 实现原理 基于数组环形队列可以使用两个指针来标记队列的头和尾,当头指针和尾指针重合时,队列为空,当尾指针前进到数组的末尾时,需要将其重置为数组的起始位置,以实现循环使用。 队列的入队操作可以分为以下几个步骤: - 检查队列是否已满,如果已满则返回错误码 - 将新的数据元素加入到队列的尾部 - 更新尾指针指向新的元素 队列的出队操作可以分为以下几个步骤: - 检查队列是否为空,如果为空则返回错误码 - 访问队列的头部元素 - 将头指针指向队列的下一个元素 - 返回头部元素的值 2. 代码实现 以下是基于数组实现环形队列的代码示例: ```cpp template<typename T> class CircularQueue { public: CircularQueue(size_t capacity) : m_capacity(capacity), m_size(0), m_head(0), m_tail(0) { m_data = new T[m_capacity]; } ~CircularQueue() { delete[] m_data; } bool enqueue(const T& element) { if (is_full()) { return false; } m_data[m_tail] = element; m_tail = (m_tail + 1) % m_capacity; ++m_size; return true; } T dequeue() { if (is_empty()) { return T(); } T ret = m_data[m_head]; m_head = (m_head + 1) % m_capacity; --m_size; return ret; } bool is_empty() const { return m_size == 0; } bool is_full() const { return m_size == m_capacity; } private: T* m_data; size_t m_capacity; size_t m_size; size_t m_head; size_t m_tail; }; ``` 3. 总结 基于数组实现环形队列可以高效地实现队列的操作,同时避免了队列内存空间的浪费。在使用环形队列时,需要注意队列的大小和容量之间的关系,以及头尾指针的更新和循环使用等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值