队列(ArrayQueue)-- 环形数组实现

环形数组队列

(数组队列的实现有多种,本文使用环形数组来模拟实现)

环形数组需要使用到一个小技巧:取模。

代码实现

/**
 * @author CXQ
 * @version 1.0
 */
public class ArrayQueueDemo {
    public static void main(String[] args){
        ArrayQueue arrayQueue = new ArrayQueue(5);
        System.out.println(arrayQueue.isEmpty() ? "为空" : "不为空");
        arrayQueue.addQueue(8);
        arrayQueue.addQueue(5);
        System.out.println(arrayQueue.isEmpty() ? "为空" : "不为空");
        System.out.println(arrayQueue.isFull() ? "为满" : "不为满");
        arrayQueue.showQueue();
    }
}

/**
 * ArrayQueue类
 */
class ArrayQueue {
    private int maxSize;
    private int front;
    private int rear;
    private int[] arrayQueue;

    /**
     * 数组队列的构造器
     */
    ArrayQueue(int maxSize) {
        //预留一个空的元素
        this.maxSize = maxSize + 1;
        arrayQueue = new int[maxSize];
        front = 0;
        rear = 0;
    }

    /**
     * 判断队列是否为空
     */
    boolean isEmpty() {
        return rear == front;
    }

    /**
     * 判断队列是否为满
     */
    boolean isFull() {
        return front == (rear + 1) % maxSize;
    }

    /**
     * 添加数据到队列
     */
    void addQueue(int value) {
        if (isFull()) {
            throw new RuntimeException("队列已满...");
        } else {
            arrayQueue[rear] = value;
            rear = (rear + 1) % maxSize;
        }
    }

    /**
     * 获取队列数据
     */
    int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列空,不可以取出元素");
        } else {
            front++;
            return arrayQueue[front];
        }
    }

    /**
     * 显示队列
     */
    void showQueue() {
        if (isEmpty()) {
            System.out.println("队列空");
        } else {
            StringBuilder stringBuilder = new StringBuilder();
            while (front != rear) {
                stringBuilder.append(arrayQueue[front]);
                front = (front + 1) % maxSize;
            }
            System.out.println("Queue[" + stringBuilder + "]");
        }
    }
}

友情链接:兄弟笔记链接

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值