队列_数组模拟队列

数组模拟队列
  • 通过front和rear控制队列的头部和尾部
  • 缺点:每次变更队列,需创建新的数组来装数据
package com.zsx.structure.queue;

public class ArrayQueueDemo {

    public static void main(String[] args) {
        //初始化队列
        ArrayQueue arrayQueue = new ArrayQueue(3);
        //队列添加数据
        arrayQueue.addQueue(11);
        arrayQueue.addQueue(22);
        arrayQueue.addQueue(33);
        //显示队列
        arrayQueue.show();

        //从队列中取出头部
        arrayQueue.getQueue();

        //显示队列数据
        arrayQueue.show();

        //显示头部数据而不取
        System.out.println(arrayQueue.peek());

        //显示队列数据
        arrayQueue.show();
        //从队列中取出头部
        arrayQueue.getQueue();

        //显示队列数据
        arrayQueue.show();
    }
}

//数组模拟一个队列
class ArrayQueue {
    //队列的容量
    private int maxSize;

    //头部指针
    private int front;

    //尾部指针
    private int rear;

    //队列-数据
    private int[] arr;

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[this.maxSize];
        front = -1;
        rear = -1;
    }

    /**
     * 添加数据到队列
     *
     * @param data
     */
    public void addQueue(int data) {
        if (isFull()) {
            throw new RuntimeException("队列满了");
        }
        //尾部指针后移
        rear++;
        //添加数据
        arr[rear] = data;
    }

    /**
     * 获取队列的数据
     */
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }

        //头部指针后移
        front++;
        //取出对应的值
        int data = arr[front];
        System.out.println("取出头部:" + data);
        //队列移除该数据
        int[] arr1 = new int[this.maxSize];
        int count = 0;
        for (int i = front; i < rear; i++) {

            arr1[count++] = arr[i];
        }
        arr = arr1;
        front--;
        rear--;
        return data;

    }

    /**
     * 显示头部数据
     *
     * @return
     */
    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        return arr[0];
    }

    /**
     * 显示队列的数据
     */
    public void show() {
        System.out.println("=======队列数据=========");
        System.out.println("最大长度为:" + this.maxSize);
        for (int i = 0; i <= rear; i++) {
            System.out.println("arr[" + i + "]:" + arr[i]);
        }
    }

    /**
     * 判断队列为满
     *
     * @return
     */
    public boolean isFull() {
        return rear == maxSize - 1;
    }

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


}

结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值