首页 > 其他分享 >队列和循环队列(ArrayQueueAndCircleQueue)

队列和循环队列(ArrayQueueAndCircleQueue)

时间:2023-11-22 11:24:05浏览次数:32  
标签:队列 System println int 循环 front ArrayQueueAndCircleQueue out

队列

数组队列

1.初始化队列

private int maxsize;//最大长度
    private int front;//指向队首的前一个位置
    private int rear;//指向队尾
    private int[] arr;

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

2.判断是否队列已满

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

3.判断队列是否为空

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

4.入队

//    入队
public void addQueue(int n) {
    if (isFull())
        throw new RuntimeException("队列已满");
    arr[++rear] = n;
}

5.出队

//    获取数据,出队
public int getQueue() {
    if (isEmpty())
        throw new RuntimeException("队列为空~~");
    return arr[++front];
}

6.显示队列所有数据

//    显示队列所有数据
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]);
    }
}

7.获取队头数据

//    获取队头数据
public int headQueue() {
    if (isEmpty())
        throw new RuntimeException("队列为空~~");
    return arr[front + 1];
}

8.测试代码

/**
 * @author 缪广亮
 * @version 1.0
 * 数组队列
 */
public class ArrayQueueDemo {
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(3);
        Scanner scanner = new Scanner(System.in);
        char key = ' ';//接收用户输入
        boolean loop = true;
        while (loop) {
            System.out.println("======a(add)======");
            System.out.println("======g(get)======");
			System.out.println("======h(head)======");
            System.out.println("======s(show)======");
            System.out.println("======e(exit)======");
            System.out.print("请输入菜单选项中的首字母操作:");
            key = scanner.next().charAt(0);
            switch (key) {
                case 'a':
                    try {
                        System.out.println("请输入加入队列的一个数:");
                        int value = scanner.nextInt();
                        arrayQueue.addQueue(value);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'g':
                    int res = 0;
                    try {
                        res = arrayQueue.getQueue();
                        System.out.println("取出的数据是:" + res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int head = arrayQueue.headQueue();
                        System.out.println("队头数据: " + head);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    System.out.println("你的输入有误,请重新输入!");
            }
        }
        System.out.println("程序退出~~~");
    }
}

循环队列

1.初始化队列

private int maxsize;
//指向队首元素,即队列的第一个元素front=0
private int front;
//指向队列的最后一个元素的后一个位置,空出一个空间为约定rear=(rear+1)%maxsize
private int rear;
private int[] arr;

public CircleQueue(int maxsize) {
    this.maxsize = maxsize;
    arr = new int[maxsize];
    front=0;
    rear=0;
}

2.判断是否队列已满

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

3.判断队列是否为空

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

4.入队

//    入队
    public void addQueue(int n) {
        if (isFull())
            throw new RuntimeException("队列已满");
        arr[rear] = n;
//        指向队列的最后一个元素的后一个位置,考虑取模
        rear = (rear + 1) % maxsize;
    }

5.获取队列的数据,出队列

 //    获取队列的数据,出队列
    public int getQueue() {
        if (isEmpty())
            throw new RuntimeException("队列为空~~");
//        分析出front是指向队列的第一个元素
//        先把front对应的值保留到一个临时变量
//        将临时变量返回
        int value = arr[front];
        //        将front后移,考虑取模
        front = (front + 1) % maxsize;
        return value;

    }

6.显示队列所有数据

//    显示队列所有数据
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空,无法遍历");
            return;
        }
//        从front开始遍历,遍历多少个元素
        for (int i = front; i < front + size(); i++) {
//            循环队列的下标要考虑取模
            System.out.printf("arr[%d]=%d\n", (i % maxsize), arr[(i % maxsize)]);
        }
    }

7.当前队列中有效个数

//    当前队列中有效个数
public int size() {
    return (rear + maxsize - front) % maxsize;
}

8.获取队头和队尾数据

//    获取队头数据
    public int headQueue() {
        if (isEmpty())
            throw new RuntimeException("队列为空~~");
        return arr[front];
    }
//    获取队尾元素
    public int lastQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空~~");
        }
        return arr[(rear-1+maxsize)%maxsize];
    }

8.测试代码

/**
 * @author 缪广亮
 * @version 1.0
 * 循环队列
 */
@SuppressWarnings({"all"})
public class CircleQueueDemo {
    public static void main(String[] args) {
        CircleQueue circleQueue = new CircleQueue(4);
        Scanner scanner = new Scanner(System.in);
        char key = ' ';//接收用户输入
        boolean loop = true;
        while (loop) {
            System.out.println("======a(add)======");
            System.out.println("======g(get)======");
            System.out.println("======h(head)======");
            System.out.println("======s(show)======");
            System.out.println("======l(last)======");
            System.out.println("======e(exit)======");
            System.out.print("请输入菜单选项中的首字母操作:");
            key = scanner.next().charAt(0);
            switch (key) {
                case 'a':
                    try {
                        System.out.println("请输入加入队列的一个数:");
                        int value = scanner.nextInt();
                        circleQueue.addQueue(value);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'g':
                    int res = 0;
                    try {
                        res = circleQueue.getQueue();
                        System.out.println("取出的数据是:" + res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int head = circleQueue.headQueue();
                        System.out.println("队头数据: " + head);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 's':
                    circleQueue.showQueue();
                    break;
                case 'l':
                    try {
                        int last = circleQueue.lastQueue();
                        System.out.println("取得的队尾数据:"+last);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    System.out.println("你的输入有误,请重新输入!");
            }
        }
        System.out.println("程序退出~~~~");
    }
}

标签:队列,System,println,int,循环,front,ArrayQueueAndCircleQueue,out
From: https://www.cnblogs.com/mglblog/p/17848548.html

相关文章

  • 实验2 C语言分支与循环基础应用编程
    实验任务11#include<stdio.h>2#include<stdlib.h>3#include<time.h>45#defineN56#defineN13747#defineN24658intmain(){9intnumber;10inti;11srand(time(0));12for(i=0;i<N;++i){13nu......
  • 【题目-理想的正方形】 二维单调队列
    理想的正方形(二维单调队列)题目acwing.1091理想的正方形题解题目很好做,主要学习一下二维单调队列的写法首先将每行各窗口内最值用单调队列维护出来,保存在rmax中接着对rmax各列,将每列最值用单调队列维护出来,保存在cmax中,最后cmax中存的就是行和列窗口乘积范围的二维区间......
  • 11.17双向循环链表应用
     #include<bits/stdc++.h>usingnamespacestd;typedefstructf{intdata;f*prior;f*next;}node,*Node;voidbuild(Nodep){intn;cin>>n;while(n--){intx;cin>>x;Nodenow=newnode()......
  • 关于一类最优解存在长度为 $k$ 的循环节的问题
    灵感来源问题形式:给定长度为\(n\)的序列,要求选出一些位置,使这些位置满足限制条件\(T\),其中\(T\)可以表述为一个长度为\(k\)的环满足条件\(T'\),选出第\(i\)个位置的收益是\(f(i\bmodk)\),求最大收益。关键在于证明一个引理:最优解一定存在长度为\(k\)的循环节。证明......
  • 单调队列优化多重背包
    多重背包题目已经很熟了我们要把它优化到O(nm)也就是对于每一个物品,我们只能够对dp数组进行一次遍历,并且不能枚举取几个物品或者说是,要在每一个状态下O(1)的找到取不同数量物品的最优解,并转移我们可以发现,其实转移的区间是非常有规律的,f[j]只能够从f[j-v[i]],f[j-2*v[i]]....f[j-c[i]*v......
  • 如何在 PHP 中使用 while 循环按 ID 列出节中的数据?
    要在PHP中使用while循环按ID列出数据,您可以按照以下步骤进行操作:创建数据库连接:首先,您需要使用适当的凭据来连接到数据库。您可以使用mysqli或PDO等库来实现数据库连接。$servername="localhost";$username="your_username";$password="your_password";$dbname......
  • 无涯教程-Sed - 循环语句
    与其他编程语言一样,SED也提供了循环和分支函数来控制执行流程。在本章中,无涯教程将探索更多有关如何在SED中使用循环和分支的信息。SED中的循环的工作方式类似于goto语句。SED可以跳到标签所标签的行,然后继续执行其余命令。在SED中,可以如下定义label :label:start:end......
  • C语言:用for循环语句编写金字塔
       今天我将继续为大家分享C语言的知识,今天要分享的内容依旧是C语言中的for循环语句中的经典例题。好了,废话少说,让我们进入今天的学习内容吧!#include<stdio.h>intmain(){inti,j,c;for(i=1;i<=10;i++)//十行的金字塔{for(j=1;j<=15-i;j++)//*前面有15-i个......
  • 遍历循环,只要有其中一个符合就退出
    使用stream流的anyMatch判断的条件里,任意一个元素成功,返回true上代码List<SectorInfo>sectorsInfo=scanResultParser.apply(scanResult);returnsectorsInfo.stream().map(sectorInfo->badSectorCountParser.apply(sectorInfo.getValue()))......
  • cmm脚本之,循环、变量
    OPEN#1test.txt/CreateLOCAL&Emdc_Rx_Timestape&Emdc_Rx_Timestape=V.VALUE(Emdc_Rx_Timestape)PRINTV.VALUE(Emdc_Rx_Timestape)"&Emdc_Rx_Timestape"RePeaT100.(IFV.VALUE(Emdc_Rx_Timestape)!=V.VALUE(Emdc_Rx_Timestape)......