数组实现队列---Java实现

版权声明:转载请标明附带连接标明出处 https://blog.csdn.net/Hollake/article/details/91039108

此代码来源于左神的视频教程

思路

采用两个指针以及队列大小的变量,start和end以及size,添加元素,end向后移动,start不动,size+1,删除元素,end不动,start后移,size-1。当end移动到arr.length时候,如果队列没有满,也就是size!=arr.length,那说明数组arr的开始位置肯定是空的,所以继续添加元素的时候end重新移动到arr的0位置。

class MyQueue{
    private int[] arr;
    private int size;
    private int start;
    private int end;
    MyQueue(int initSize){
        if (initSize < 0) {
            throw new IllegalArgumentException("the init size must more than 0");
        }
        arr = new int[initSize];
        start = 0;
        end = 0;
        size = 0;
    }

    public void push(int obj) {
        if (size == arr.length) {
            throw new  ArrayIndexOutOfBoundsException("The queue is full");
        }
        arr[end] = obj;
        end = end == arr.length - 1 ? 0 : end + 1;
        size++;
    }

    public int poll() {
        if (size == 0) {
            throw new ArrayIndexOutOfBoundsException("The queue is empty");
        }
        int tmp = start;
        start = start == arr.length - 1 ? 0 : start + 1;
        size--;
        return arr[tmp];
    }
    public Integer peek(){
        if (size == 0) {
            return null;
        }
        return arr[start];
    }
}

猜你喜欢

转载自blog.csdn.net/Hollake/article/details/91039108