左神算法笔记-实现循环队列

65 阅读1分钟
class MyCircularQueue {

    int[] queue;
    // size:队列中实际的数量,head:头,tail:尾,limit:数量限制
    int size, head, tail, limit;

    public MyCircularQueue(int k) {
        queue = new int[k];
        head = tail = size = 0;
        limit = k;
    }

    /**
     * 队列添加一个值,成功返回true
     *
     * @param value
     * @return
     */
    public boolean enQueue(int value) {
        // 满返回
        if (isFull()) {
            return false;
        }
        queue[tail] = value;
        // 放在尾部,尾部加一。若结束回到0位置
        tail = tail == limit - 1 ? 0 : (tail + 1);
        size++;
        return true;
    }

    /**
     * 队列弹出一个值
     *
     * @return
     */
    public boolean deQueue() {
        // 空返回
        if (isEmpty()) {
            return false;
        }
        // 弹出头,头加一。若结束回到0位置
        head = head == limit - 1 ? 0 : (head + 1);
        size--;
        return true;
    }

    /**
     * 返回队列头部的数字(不弹出),如果没有数返回-1
     */
    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        return queue[head];
    }

    /**
     * 返回队列尾部的数字(不弹出),如果没有数返回-1
     */
    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        // 尾部在0位置,上一个加入的数字在limit-1;否则在尾部-1位置
        int last = tail == 0 ? (limit - 1) : (tail - 1);
        return queue[last];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == limit;
    }
}