Java数据结构与算法——队列

news/2025/2/23 23:02:05

1.简介

队列是一个有序列表,可以用数组或是链表来实现。遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出。

队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图, 其中 maxSize 是该队列的最大容量。

因为队列的输出、输入是分别从前后端来处理,因此需要两个变量 front及 rear分别记录队列前后端的下标,front 会随着数据输出而改变,而 rear则是随着数据输入而改变,如图所示:


2.数组模拟普通队列

当我们将数据存入队列时称为”addQueue”,addQueue 的处理需要有两个步骤:思路分析

将尾指针往后移:rear+1 , 当front == rear 【空】

若尾指针 rear 小于队列的最大下标 maxSize-1,则将数据存入 rear所指的数组元素中,否则无法存入数据。 rear  == maxSize - 1[队列满]

package com.szh.queue;

import java.util.Scanner;

/**
 *
 */
class ArrayQueue {
    private Integer maxSize; //队列的最大容量
    private Integer front;   //队列头
    private Integer rear;    //队列尾
    private Integer[] arr;   //数组模拟队列

    public ArrayQueue(Integer maxSize) {
        this.maxSize = maxSize;
        arr = new Integer[this.maxSize]; //创建队列
        this.front = -1; //指向队列头的前一个位置
        this.rear = -1;  //指向队列尾的当前位置
    }

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

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

    //向队列中添加数据
    public void addQueue(int n) {
        if (isFull()) {
            System.out.println("队列已满,无法继续添加数据。");
            return;
        }
        arr[++rear] = n;
    }

    //从队列中取出数据
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列已空,无法继续取出数据。");
        }
        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]);
        }
    }

    //显示队列的头数据
    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(3);
        Scanner input = new Scanner(System.in);
        char key = ' ';
        boolean loop = true;
        //菜单循环
        while (loop) {
            System.out.println("s(show): 显示队列");
            System.out.println("e(exit): 退出程序");
            System.out.println("a(add): 添加数据到队列");
            System.out.println("g(get): 从队列取出数据");
            System.out.println("h(head): 查看队列头的数据");
            key = input.next().charAt(0); //从控制台接收一个字符
            switch (key) {
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.print("请输入要添加的数据:");
                    int value = input.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    int res = arrayQueue.getQueue();
                    System.out.println("取出的数据是:" + res);
                    break;
                case 'h':
                    int ans = arrayQueue.headQueue();
                    System.out.printf("队列头的数据是%d\n", ans);
                    break;
                case 'e':
                    input.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出....");
    }
}


3.数组模拟环形队列

对前面的数组模拟队列的优化,充分利用数组. 因此将数组看做是一个环形的。(通过取模的方 式来实现即可)

分析说明:尾索引的下一个为头索引时表示队列满,即将队 列容量空出一个作为约定,这个在做判断队列满的 时候需要注意 (rear + 1) % maxSize == front 满]

rear == front [空]

package com.szh.queue;

import java.util.Scanner;

/**
 *
 */
class CircleArrayQueue {
    private int maxSize; // 表示数组的最大容量
    //front 变量的含义做一个调整: front 就指向队列的第一个元素, 也就是说 arr[front] 就是队列的第一个元素
    //front 的初始值 = 0
    private int front;
    //rear 变量的含义做一个调整:rear 指向队列的最后一个元素的后一个位置. 因为希望空出一个空间做为约定.
    //rear 的初始值 = 0
    private int rear; // 队列尾
    private int[] arr; // 该数据用于存放数据, 模拟队列

    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        this.front = 0;
        this.rear = 0;
    }
    //判断队列是否已满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

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

    //向队列中添加数据
    public void addQueue(int n) {
        if (isFull()) {
            System.out.println("队列已满,无法继续添加数据。");
            return;
        }
        //直接将数据加入
        arr[rear] = n;
        //将 rear 后移, 这里必须考虑取模
        rear = (rear + 1) % maxSize;
    }

    //从队列中取出数据
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列已空,无法继续取出数据。");
        }
        //这里需要分析出 front 是指向队列的第一个元素
        //先把 front 对应的值保留到一个临时变量
        int res = arr[front];
        //将 front 后移, 考虑取模
        front = (front + 1) % maxSize;
        //将临时保存的变量返回
        return res;
    }

    //显示队列中所有的数据
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列空的,没有数据....");
            return;
        }
        int num = size();
        for (int i = front; i < front + num; i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    //显示队列的头数据
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列空的,没有数据....");
        }
        return arr[front];
    }

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

public class CircleArrayQueueDemo {
    public static void main(String[] args) {
        //创建一个队列, 说明设置4, 其队列的有效数据最大是3
        CircleArrayQueue arrayQueue = new CircleArrayQueue(4);
        Scanner input = new Scanner(System.in);
        char key = ' ';
        boolean loop = true;
        //菜单循环
        while (loop) {
            System.out.println("s(show): 显示队列");
            System.out.println("e(exit): 退出程序");
            System.out.println("a(add): 添加数据到队列");
            System.out.println("g(get): 从队列取出数据");
            System.out.println("h(head): 查看队列头的数据");
            key = input.next().charAt(0); //从控制台接收一个字符
            switch (key) {
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.print("请输入要添加的数据:");
                    int value = input.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    int res = arrayQueue.getQueue();
                    System.out.println("取出的数据是:" + res);
                    break;
                case 'h':
                    int ans = arrayQueue.headQueue();
                    System.out.printf("队列头的数据是%d\n", ans);
                    break;
                case 'e':
                    input.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出....");
    }
}


http://www.niftyadmin.cn/n/711076.html

相关文章

tomcat启动不了的问题

tomcat启动的几个问题 1、端口冲突 2、非端口冲突&#xff0c;需要加入配置host文件 日志文件&#xff1a; 解决办法&#xff1a;https://blog.csdn.net/u012949658/article/details/55232555/ 转载于:https://www.cnblogs.com/wuzm/p/11224569.html

Linux IO模式-阻塞io、非阻塞io、多路复用io

一 概念说明 在进行解释之前&#xff0c;首先要说明几个概念&#xff1a; - 用户空间和内核空间 - 进程切换 - 进程的阻塞 - 文件描述符 - 缓存 I/O 用户空间与内核空间 现在操作系统都是采用虚拟存储器&#xff0c;那么对32位操作系统而言&#xff0c;它的寻址空间&#xff08…

Java数据结构与算法——递归与回溯

1.什么是递归&#xff1f; 简单的说: 递归就是方法自己调用自己,每次调用时传入不同的变量.递归有助于编程者解决复杂的问题,同时可以让代码变得简洁。 看个实际应用场景&#xff0c;迷宫问题(回溯)&#xff0c; 递归(Recursion) 我列举两个小案例,来帮助大家理解递归&#xff…

Layout 实现三栏布局的几种方法

https://github.com/ljianshu/Blog/issues/14 布局参考 https://github.com/ljianshu/Blog/issues/38 响应式那点事儿 https://github.com/Fundebug/fundebug-blog/issues/68 技术博客那点事儿转载于:https://www.cnblogs.com/reeber/p/11231659.html

Java设计模式(八)观察者模式 迭代器模式

&#xff08;十五&#xff09;观察者模式 观察者模式&#xff0c;定义对象间一对多关系&#xff0c;一个对象状态发生改变&#xff0c;全部依赖于它的对象都收到通知而且自己主动更新&#xff0c;观察者与被观察者分开。比如邮件订阅、RSS订阅&#xff0c;假设有更新就会邮件通…

Java数据结构与算法——冒泡排序

1.关于排序 排序也称排序算法 (Sort Algorithm)&#xff0c;排序是将一 组数据&#xff0c;依指定的顺序进行排列 的过程。 排序的分类&#xff1a; 内部排序: 指将需要处理的所有数据都加载 到内部存储器中进行排序。外部排序法&#xff1a;数据量过大&#xff0c;无法全部加…

Zend Optimizer not installed解决方案

Zend Optimizer not installed解决方案 zend optimizer主要有两个功能&#xff1a; 1、提升PHP程序性能&#xff1b; 2、运行经过zend加密的PHP文件。 今天下了个CMS安装的时候碰到了个棘手问题&#xff0c;安装了N多次ZendOptimizer-3.3.0a-Windows-i386.exe就是不行&#xff…

RandomAccessFile

2019独角兽企业重金招聘Python工程师标准>>> RandomAccessFile是用来访问那些保存数据记录的文件的&#xff0c;你就可以用seek( )方法来访问记录&#xff0c;并进行读写了。这些记录的大小不必相同&#xff1b;但是其大小和位置必须是可知的。但是该类仅限于操作文…