循环队列笔记

本文详细介绍了循环队列的概念,包括其作为顺序队列的一种避免假溢出的改进方式,以及如何判断队列为空和队满的条件。文章还提供了循环队列的代码实现,帮助读者深入理解这一数据结构。
摘要由CSDN通过智能技术生成

循环队列(Circular Queue

顺序队列

顺序队列是一种只能在表的一端进行插入运算,在表的另一端进行删除运算的线性表(头删尾插)会出现假溢出。

Rear = N - 1 时队满。

循环队列

Front == Rear 时队列为空
Front == (Rear +1 ) % queueSize 时队满

人为浪费一个空间。
侵删

代码实现

class MyCircularQueue {
    
    private int[] queue;
    private int head = 0;
    private int tail = 0;
    private int size;

    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
        this.queue = new int[k + 1]; /*需要一位空出区分队满和队空*/
        this.size = k + 1;/*容量为k 但大小是k+1*/
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if(isFull()){
            return false;
        }
        queue[tail] = value;
        tail = (tail + 1) % size;
        return true;
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
        if(isEmpty()) return false;
        head = (head + 1) % size;
        return true;
    }
    
    /** Get the front item from the queue. */
    public int Front() {
        return isEmpty() ? -1 : queue[head];
    }
    
    /** Get the last item from the queue. */
    public int Rear() {
        return isEmpty() ? -1 : queue[(tail + size - 1) % size];
    }
    
    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
        return head == tail;
    }
    
    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
        return (tail + 1) % size == head;
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * boolean param_1 = obj.enQueue(value);
 * boolean param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * boolean param_5 = obj.isEmpty();
 * boolean param_6 = obj.isFull();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值