数据结构 —— 队列

本文通过Java代码展示了数组和环形数据结构实现队列的过程,详细解释了队列的工作原理及其在银行排队、购票等场景的应用。在初始的数组队列基础上,进一步优化为环形队列,解决了数组无法复用的问题,并提供了完整的菜单驱动的测试案例。
摘要由CSDN通过智能技术生成

队列(Queue)

队列的应用场景

银行排队案例,买票案例

队列概述

  • 队列是一个有序列表,可以用数组或是链表来表现
  • 遵循先进先出的元组
队列的实现方式
数组形式

image-20201016083130818

image-20201016083429638

代码实现

package com.why.data_structure.queue;

import java.awt.*;
import java.util.Arrays;
import java.util.Scanner;

/**
 * @Description TODO 用数组模拟队列
 * @Author why
 * @Date 2020/10/16 8:40
 * Version 1.0
 **/
public class ArrayQueueDemo {
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(20);
        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("g(get):从队列取出数据");
            System.out.println("h(head):查看队列头部数据");
            key = scanner.next().charAt(0);//接受一个字符
            switch (key){
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("输入一个数");
                    int value = scanner.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = arrayQueue.subQueue();
                        System.out.printf("取出的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = arrayQueue.headQueue();
                        System.out.printf("数据头数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    System.out.println("程序退出");
                    break;
                default:
                    break;

            }
        }
    }
}

//编写一个数组模拟队列的类
class ArrayQueue{
    private int maxSize;//数组最大容量
    private int front;//队列头
    private int rear;//队列尾部
    private int[] arr;//存放数据,模拟队列

    /**
     * 队列初始化,构造队列
     * @param maxSize
     */
    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = -1;//指向队列头部
        rear = -1;//指向队列尾部
    }

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

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

    /**
     * 入队,添加数据
     * @param n
     */
    public void addQueue(int n){
        //判满
        if (isFull()){
            System.out.println("队列已满!不可添加数据!");
            return;
        }
        rear+=1;//rear后移
        arr[rear] = n;
    }

    /**
     * 出队获得队列的值
     * @return
     */
    public int subQueue(){
        //判空
        if (isEmpty()){
            throw new RuntimeException("队列为空!");
        }
        return arr[front+=1];
    }

    /**
     * 显示队列所有数据
     */
    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("队列空");
        }
        return arr[front+1];
    }
    public ArrayQueue() {
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    public int getFront() {
        return front;
    }

    public void setFront(int front) {
        this.front = front;
    }

    public int getRear() {
        return rear;
    }

    public void setRear(int rear) {
        this.rear = rear;
    }

    public int[] getArr() {
        return arr;
    }

    public void setArr(int[] arr) {
        this.arr = arr;
    }

    @Override
    public String toString() {
        return "ArrayQueue{" +
                "maxSize=" + maxSize +
                ", front=" + front +
                ", rear=" + rear +
                ", arr=" + Arrays.toString(arr) +
                '}';
    }
}

问题分析

  • 目前数组使用一次就不能使用,达不到复用的效果
  • 使用算法,改进成环形队列
数组模拟环形队列

思路如下

  1. front变量含义做调整,front指向数组队列的第一个元素,也就是说arr[front]是队列的第一个元素

  2. rear变量含义做调整,rear指向队列的最后一个元素的后一个位置,希望空出一个空间作为一个约定

  3. 初始化 front = 0;rear = 0;

  4. 当队列满时,条件是(rear+1)% maxSize == front(满)

  5. 当队列为空时,条件是rear == front(空)

  6. 队列中有效的数据个数为:(rear+maxSize-front)% maxSize

环形队列代码实现

package com.why.data_structure.queue;

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

/**
 * @Description TODO 环形队列实现与测试
 * @Author why
 * @Date 2020/10/16 11:01
 * Version 1.0
 **/
public class RingQueueDemo {
    public static void main(String[] args) {

        //设置5有效数据最大为4,有一个预留空间
        RingQueue ringQueue = new RingQueue(5);
        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("g(get):从队列取出数据");
            System.out.println("h(head):查看队列头部数据");
            key = scanner.next().charAt(0);//接受一个字符
            switch (key) {
                case 's':
                    ringQueue.getAll();
                    break;
                case 'a':
                    System.out.println("输入一个数");
                    int value = scanner.nextInt();
                    ringQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = ringQueue.subQueue();
                        System.out.printf("取出的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = ringQueue.headQueue();
                        System.out.printf("数据头数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    System.out.println("程序退出");
                    break;
                default:
                    break;
            }
        }
    }
}

class RingQueue{
    private int front;//头指针
    private int  rear;//尾指针
    private int[] arrayArr;//存放数据的数组
    private int maxSize;//最大容量

    /**
     * 初始化设置最大容量,将front = 0; rear = 0
     * @param maxSize
     */
    public RingQueue(int maxSize) {
        this.maxSize = maxSize;
        front = 0;
        rear = 0;
        arrayArr = new int[maxSize];
    }

    /**
     * 判满
     */
    public boolean isFull(){
        return (rear +1) % maxSize == front;
    }

    /**
     * 判空
     */
    public boolean isEmpty(){
        return rear == front;
    }

    /**
     * 入队,添加数据
     * @param n
     */
    public void addQueue(int n){
        if (isFull()){
            System.out.println("队列已满,不可添加数据");
            return;
        }
        arrayArr[rear] = n;
        rear = (rear+1) % maxSize;
    }

    /**
     * 出队
     * @return
     */
    public int subQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,无数据可取");
        }
        int value = arrayArr[front];
        front = (front+1)%maxSize;
        return value;
    }

    /**
     * 输出所有数据
     */
    public void getAll(){
        //遍历
        if (isEmpty()){
            System.out.println("队列空");
            return;
        }
        //思路
        //从front开始遍历遍历(rear+maxSize-front)% maxSize个元素
        for (int i = front; i <front+size(); i++) {
            System.out.printf("arr[%d]=%d\n",i%maxSize,arrayArr[i%maxSize]);
        }
    }

    /**
     * 显示头数据
     * @return
     */
    public int headQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列空");
        }
        return arrayArr[front];
    }

    public int size(){
        return (rear+maxSize-front)% maxSize;
    }

    public RingQueue() {
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值