怎么用 " 数组 " 实现“ 循坏队列 ”从而实现优化?看这!!

本文介绍了如何利用数组构建循环队列以优化内存开销。队列遵循先进先出原则,常见操作包括入队、出队、判断队列状态等。文章详细讲解了Java内置队列的初始化、元素添加、获取队首和队尾元素以及出队的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

队列

队列的特点是先进先出,犹如排队的情景
在这里插入图片描述
而队列的操作有:入队,出队,判断队列是否为空,判断队列是否满队,取队列的第一个,取队尾的元素。当存储的数据很多时,我们用很大的数组去存数据时,会造成很大的内存开销,这里使用循坏队列去存储,它的实现原理如下:


class MyCircularQueue {
    private int [] data;//定义一个数组实现队列
    private int head;//定义一个整型作用为头指针
    private int tail;//定义一个整型作用为尾指针
    private int size;//定义一个整型作用为队列大小

    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
       data = new int[k];//初始化数组
       size=k;
       head=-1;//定义初始状态,即为空的状态
       tail=-1;//定义初始状态,即为空的状态
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if(isFull()==true){//插入前,先判断是否满队
        return false;
        }
        if(isEmpty()==true){//插入前,先判断队列是否为空,如果是,准备插入(使head进入正常下标范围,指向第一个数)
        head=0;
        }
        tail=(tail+1)%size;//加一取模
        data[tail]=value;
        return true;
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
       if(isEmpty()==true){//出队前,先判断队列是否为空
       return false;
       }
       if(head==tail){//当队列的只有一个元素时的状态,即head=tail
       head=-1;//分别置为空队列的状态
       tail=-1;
        return true;
       }
       head=(head+1)%size;//头指针加一取模
       return true;
    }
    
    /** Get the front item from the queue. */
    public int Front() {
        if(isEmpty()==true){//先判断队列是否为空
        return -1;
        }
        return data[head];
    }
    
    /** Get the last item from the queue. */
    public int Rear() {//先判断队列是否为空
       if(isEmpty()==true){
       return -1;
       }
       return data[tail];
    }
    
    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {//队列为空时head与tail都为-1
       return head==-1;
    }
    
    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
       return (tail+1)%size==head;
    }
}



java内置队列的使用

队列初始化

Queue<Integer>q =new LinkedList();

入队

q.offer();

取出队列第一个元素

q.peek();

出队

q.poll();

取队列的大小

q.size();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值