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

队列

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


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();
发布了57 篇原创文章 · 获赞 5 · 访问量 2808

猜你喜欢

转载自blog.csdn.net/qq_43520913/article/details/105363042