一、队列

  • 特点:先入先出
  • 分析:因为队列队首队尾都可以操作,所以需要两个变量模拟指针 frontrear 分别指向首元素的前一个位置和尾元素,使用数组实现队列
  • 入队列:rear后移,元素入队
  • 出队列:front后移,元素出队

二、代码实现

public class ArrayQueue{
    /**
     * 队列最大容量
     */
    private int maxSize;
    /**
     * 队列头指针(指向首元素的前一个位置)
     */
    private int front;
    /**
     * 队列尾指针(指向尾元素)
     */
    private int rear;
    /**
     * 数组模拟队列容器
     */
    private int[] arr;

    /**
     * 初始化队列
     * @param maxSize int
     */
    public ArrayQueue(int maxSize){
        this.maxSize = maxSize;
        arr = new int[maxSize];
        //初始化状态下头指针与尾指针相同,均为-1
        front = rear = -1;
    }

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

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

    /**
     * 入队列
     * @param data int
     */
    public void addQueue(int data){
        //队满不能入队
        if(isFull()){
            throw new RuntimeException("队列已满,无法加入数据!");
        }
        //rear后移,元素入队列
        arr[++rear] = data;
    }

    /**
     * 出队列
     * @return int
     */
    public int getQueue(){
        //队空不能出队
        if(isEmpty()){
            throw new RuntimeException("队列已空,无法取得数据!");
        }
        //front后移,元素出队列
        return arr[++front];
    }

    /**
     * 遍历队列所有元素
     */
    public void showQueue(){
        //队空无需遍历
        if(isEmpty()){
            System.out.println("队列为空!");
            return ;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
    }

    /**
     * 获取队首元素
     * @return int
     */
    public int headQueue(){
        //队空不返回
        if(isEmpty()){
            throw new RuntimeException("队列为空!");
        }
        return arr[front+1];
    }
}

三、测试队列功能

public class ArrayQueueDemo {
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(10);
        for (int i = 0; i < 10; i++) {
            arrayQueue.addQueue(10);
        }
        arrayQueue.showQueue();
        // arrayQueue.addQueue(10);
        for (int i = 0; i < 10; i++) { 
            arrayQueue.getQueue();
        }
        // arrayQueue.getQueue();
        System.out.println(arrayQueue.isEmpty());
        System.out.println(arrayQueue.isFull());
        System.out.println(arrayQueue.headQueue());
    }
}

四、控制台结果

10	10	10	10	10	10	10	10	10	10	true
true
Exception in thread "main" java.lang.RuntimeException: 队列为空!
	at com.zhiyuan.datastructure.queue.array.ArrayQueue.headQueue(ArrayQueue.java:100)
	at com.zhiyuan.datastructure.queue.array.ArrayQueueDemo.main(ArrayQueueDemo.java:22)

原文作者:絷缘
作者邮箱:zhiyuanworkemail@163.com
原文地址:https://zhiyuandnc.github.io/IjOXWGTmT/
版权声明:本文为博主原创文章,转载请注明原文链接作者信息