622. 设计循环队列

public class Algorithm {

    public static void main(String[] args) {

        MyCircularQueue queue = new MyCircularQueue(5);

        for (int i = 0; i < 6; i++) {
            System.out.println(queue.enQueue(i));
        }

        System.out.println(queue.Front());
        System.out.println(queue.Rear());

        System.out.println(queue.deQueue());

        System.out.println(queue.isEmpty());
    }
}

class MyCircularQueue {

    int[] data;
    int size;
    int front;
    int tail;

    public MyCircularQueue(int k) {

        data = new int[k];
        front = 0;
        tail = 0;
        size = 0;
    }

    public boolean enQueue(int value) {

        if (size == data.length){
            return false;
        }

        data[tail] = value;
        tail = (tail + 1) % data.length;
        size++;

        return true;
    }

    public boolean deQueue() {

        if (size == 0){
            return false;
        }

        front = (front + 1) % data.length;
        size--;

        return true;
    }

    public int Front() {

        if (isEmpty()) {
            return -1;
        }
        return data[front];
    }

    public int Rear() {

        if (isEmpty()) {
            return -1;
        }

        if (tail == 0) {
            return data[data.length - 1];
        }

        return data[tail - 1];
    }

    public boolean isEmpty() {

        return size == 0;
    }

    public boolean isFull() {

        return size == data.length;
    }
}

https://leetcode-cn.com/problems/design-circular-queue/

posted @ 2021-10-15 15:13  振袖秋枫问红叶  阅读(28)  评论(0)    收藏  举报