栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

尚硅谷数据结构循环数组队列(问题的看法)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

尚硅谷数据结构循环数组队列(问题的看法)

前言

提示:看了老师视频有些疑惑:这里我自己看法

主要参考了尚硅谷韩老师视频和大话数据结构p115


一、直接上代码
package com.QueueStudy;


public class CircleArrayQueue {
    private int maxSize;//表示数组的最大容量
    private int front;//指向队列头
    
    private int rear;//队列尾的下一个元素

    private int[] arr;//该数据用于存放数据,模拟队列




    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
        front = 0;//指向队列头部,分析出front是指向队列头的前一个位置。
        rear = 0;//指向队列尾,指向队列尾的数据(即就是队列最后一个数据)

    }

    //判断队列是否满

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

    //添加数据到队列

    
    public void addQueue(int n){
        if (ifFull()){
            System.out.println("队列满,不能加入数据");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    //获取队列的数据,出队列
    public int getQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列空,不能取出数据");
        }
        int temp = arr[front];
        front = (front + 1) % maxSize;
        return temp;
    }


    //显示队列的所有数据

    
    public void show(){
        if (isEmpty()){
            System.out.println("队列空的,没有数据");
        }
        for (int i = front;i < front + getSize();i++){
            System.out.print(arr[i % maxSize] + " ");

        }

    }

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

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



}
class QueueTest(){

	@Test
    public void testCircleArrayQueue(){

        CircleArrayQueue queue = new CircleArrayQueue(3);
        queue.addQueue(1);
        queue.addQueue(2);
        //注意这时候数组还有1个空位置,但是这时候我们约定数组已经满了
        int queueQueue = queue.getQueue();
        System.out.println("获取1个元素 " + queueQueue);
        //把3插入下表2数组中 数组0空
        queue.addQueue(3);

        queue.show();
    }
}
总结

这是我自己一些看法
内容参考尚硅谷韩老师数据结构与算法
代码注释中参考大话数据结构p115

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/988388.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号