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

Java实现队列

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

Java实现队列

 使用数组简单模拟队列

缺点:无法再次利用已经取出元素的位置,因为front一直向数组末端移动

public class ArrQueue {
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(5);
        //测试方法
        arrayQueue.addQueue(1);
        arrayQueue.addQueue(2);
        arrayQueue.addQueue(3);
        arrayQueue.showQueue();
        System.out.println("----------------------------");

        System.out.println(arrayQueue.getQueue());
        System.out.println(arrayQueue.headQueue());
        arrayQueue.showQueue();
        System.out.println("----------------------------");

        arrayQueue.addQueue(4);
        arrayQueue.addQueue(5);
        System.out.println(arrayQueue.isFull());
        System.out.println(arrayQueue.addQueue(6));
        System.out.println("----------------------------");

        System.out.println(arrayQueue.getQueue());
        System.out.println(arrayQueue.getQueue());
        System.out.println(arrayQueue.getQueue());
        System.out.println(arrayQueue.getQueue());
//        System.out.println(arrayQueue.getQueue()); //Exception 队列为空,无法删除
        System.out.println(arrayQueue.isEmpty());
        System.out.println("----------------------------");

    }

}

class ArrayQueue {
    private int maxSize;//最大容量
    private int front;//队头元素的前一个位置
    private int rear;//队尾
    private int[] arr;//该数组用于存放数据,模拟队列

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

    
    public boolean isFull() {
        return rear == maxSize - 1;
    }

    
    public boolean isEmpty() {
        return front == rear;
    }

    
    public boolean addQueue(int n) {
        //判断队列是否为满
        if (isFull())
            return false;
        arr[++rear] = n;
        return true;
    }

    
    public int getQueue() {
        if (isEmpty())
            throw new RuntimeException("队列为空");
        return arr[++front];
    }

    
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空");
        }
        for (int i = front + 1; i <= rear; i++)
            System.out.println(arr[i]);
    }

    
    public int headQueue() {
        if (isEmpty())
            throw new RuntimeException("队列为空");
        return arr[front + 1];
    }


}

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

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

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