數組實現隊列---Java實現

此代碼來源於左神的視頻教程

思路

採用兩個指針以及隊列大小的變量,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];
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章