《Java数据结构与算法》入门篇:队列

介绍

  1. 队列是一个有序列表,可以用数组或是链表来实现;
  2. 遵循先入先出的原则。即:先存入队列的数据,要先取出,后存入的要后取出;
  3. 示意图:(使用数组模拟队列示意图)
    在这里插入图片描述

数组实现队列

思路分析

  • 队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如上图,其中maxSize是该队列的最大容量。
  • 因为队列的输出、输入是分别从前后端来处理,因此需要两个变量frontrear分别记录队列前后端的下标,front会随着数据的输出而改变,rear则是随着数据的输入而改变(如上图所示)
  • 当我们将数据存入队列时称为“addQueueu”,addQueue的处理需要两个步骤:
    1. 将尾指针往后移动:rear = rear + 1,当front == rear时,则表示当前队列为空
    2. 若尾指针rear小于队列的最大下标maxSize-1,则将数据存入rear所指的数组元素中,否则无法存入数据。当rear == maxSize - 1时,则表示当前队列已满

代码实现

public class ArrayQueueDemo {

    public static void main(String[] args) {

        // 创建一个队列
        ArrayQueue queue = new ArrayQueue(3);

        // 接收用户输入
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        // 输出一个菜单
        while (loop) {
            System.out.println("s(show): 显示队列");
            System.out.println("e(exit): 退出程序");
            System.out.println("a(add): 添加数据到队列");
            System.out.println("p(pop): 从队列取出数据");
            System.out.println("h(head): 查看队列头的数据");
            key = scanner.next().charAt(0);
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("输出一个数");
                    int value = scanner.nextInt();
                    queue.addQueue(value);
                    break;
                case 'p':
                    try {
                        int res = queue.popQueue();
                        System.out.printf("取出的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = queue.headQueue();
                        System.out.printf("队列头的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }

            System.out.println();
            System.out.println();
            System.out.println();
        }

        System.out.println("程序退出~~");
    }

}


/**
 * 队列对象
 */
class ArrayQueue {

    /**
     * 队列的最大容量
     */
    private int maxSize;

    /**
     * 队列头
     */
    private int front;

    /**
     * 对列尾
     */
    private int rear;

    /**
     * 存放数据的队列
     */
    private int[] arr;

    /**
     * 创建队列构造器
     *
     * @param maxSize
     */
    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];

        // 指向队列头部,根据前面的分析,front是指向队列头的前一个位置
        this.front = -1;

        // 指向队列尾部,也就是队列最后一个数据,初始情况下与front一致
        this.rear = -1;
    }

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

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

    /**
     * 向对列中添加数据
     *
     * @param n
     */
    public void addQueue(int n) {
        // 先判断队列是否已满
        if (isFull()) {
            System.out.println("队列满,不能添加数据~~~~~~~~~~~~~~~~~~~~");
            return;
        }

        // 队列未满,则添加数据

        // 先将尾部指针向后移动1位
        rear++;

        // 赋值
        this.arr[rear] = n;
    }

    /**
     * 从队列中取出数据
     *
     * @return
     */
    public int popQueue() {
        // 先判断队列是否为空
        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.printf("arr[%d]=%d\n", i, arr[i]);
        }

    }

    /**
     * 显示队列的头数据,注意不是取出数据
     *
     * @return
     */
    public int headQueue() {
        // 判断队列是否为空
        if (isEmpty()) {
            throw new RuntimeException("队列空,不能取出数据~~~~~~~~~~~~~~~~~~~~");
        }

        // 注意:此处并没有移动"front",要看清和"popQueue"中的区别
        return this.arr[front + 1];
    }

}

问题分析并优化

  1. 目前数组使用一次就不能使用了,没有达到复用的效果
  2. 将这个数组使用算法,改进成一个环形队列,取模:%

数组实现环形队列

分析说明

  1. 尾索引的下一个位头索引时表示队列已满,即将队列容量空出一个作为约定,这个在做判断队列满的时候需要注意:(rear + 1) % maxSize == front,即表示为队列已满
  2. 判断队列为空的方式仍然是 rear == front

思路分析

  1. front变量的含义做一个调整:front就指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素,front的初始值为0
  2. rear变量的含义做一个调整:rear指向队列的最后一个元素的后一个位置,因为希望空出一个空间作为约定,rear的初始值为0
  3. 队列已满的条件是:(rear + 1) % maxSize == front
  4. 队列为空的条件是:rear == front
  5. 队列中有效数据的个数是:(rear + maxSize - front) % maxSize
  6. 我们可以在原来队列的基础上进行修改,得到一个环形队列

代码实现

public class CircleArrayQueueDemo {

    public static void main(String[] args) {

        // 创建一个队列
        // 注意:这里设置为4,队列中有效数据个数最大是3
        CircleArray queue = new CircleArray(4);

        // 接收用户输入
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        // 输出一个菜单
        while (loop) {
            System.out.println("s(show): 显示队列");
            System.out.println("e(exit): 退出程序");
            System.out.println("a(add): 添加数据到队列");
            System.out.println("p(pop): 从队列取出数据");
            System.out.println("h(head): 查看队列头的数据");
            key = scanner.next().charAt(0);
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("输出一个数");
                    int value = scanner.nextInt();
                    queue.addQueue(value);
                    break;
                case 'p':
                    try {
                        int res = queue.popQueue();
                        System.out.printf("取出的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = queue.headQueue();
                        System.out.printf("队列头的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }

            System.out.println();
            System.out.println();
            System.out.println();
        }

        System.out.println("程序退出~~");
    }

}


class CircleArray {


    /**
     * 队列的最大容量
     */
    private int maxSize;

    /**
     * 队列头
     */
    private int front;

    /**
     * 对列尾
     */
    private int rear;

    /**
     * 存放数据的队列
     */
    private int[] arr;


    /**
     * 创建队列构造器
     *
     * @param maxSize
     */
    public CircleArray(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];

        // front 变量的含义做一个调整: front 就指向队列的第一个元素, 也就是说 arr[front] 就是队列的第一个元素
        this.front = 0;

        // rear 变量的含义做一个调整:rear 指向队列的最后一个元素的后一个位置
        this.rear = 0;
    }


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

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


    /**
     * 向对列中添加数据
     *
     * @param n
     */
    public void addQueue(int n) {
        // 先判断队列是否已满
        if (isFull()) {
            System.out.println("队列满,不能添加数据~~~~~~~~~~~~~~~~~~~~");
            return;
        }

        // 队列未满,则添加数据

        // 先赋值
        this.arr[rear] = n;

        // 再将尾部指针向后移动1位,需要进行取模
        rear = (rear + 1) % maxSize;
    }


    /**
     * 从队列中取出数据
     *
     * @return
     */
    public int popQueue() {
        // 先判断队列是否为空
        if (isEmpty()) {
            throw new RuntimeException("队列空,不能取出数据~~~~~~~~~~~~~~~~~~~~");
        }

        // 队列中存在数据,则可以取出

        // 这里需要分析出:front指向队列中的第一个元素

        // 1. 先把front对应的值取出来保存到一个临时变量
        int temp = arr[front];

        // 2. 将front向后移动1位,同样需要考虑取模
        front = (front + 1) % maxSize;

        // 3. 将临时保存的值返回
        return temp;
    }


    /**
     * 求出当前队列有效数据的个数
     *
     * @return
     */
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    /**
     * 展示队列中的所有数据
     */
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列空的,没有数据~~~~~~~~~~~~~~~~~~~~~~");
            return;
        }

        // 遍历
        for (int i = front; i < front + size(); i++) {
            // 注意遍历的时候,下标都要进行取模
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }

    }

    /**
     * 显示队列的头数据,注意不是取出数据
     *
     * @return
     */
    public int headQueue() {
        // 判断
        if (isEmpty()) {
            throw new RuntimeException("队列空的,没有数据~~");
        }
        return arr[front];
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值