基於數組實現簡單的隊列

/**
 * @Description 基於數組實現簡單的隊列(先進先出)
 * @auther Eleven
 * @create 2020-04-02 23:40
 **/
public class MyQueue {

    int[] elements;


    public MyQueue() {
        //初始化的時候定義數組長度爲0,防止下面調用的時候報空指針異常
        this.elements = new int[0];
    }

    //入隊
    public void add(int element){
        //創建一個新數組用於接受需要入隊的數據和原先的數組 新數組的長度爲原先數組長度加+1
        int[] newArr=new int[elements.length+1];
        //將原先數組遍歷,並且賦值給到新的數組
        for (int i=0;i<elements.length;i++){
            newArr[i]=elements[i];
        }
        //將需要壓入的數據賦值給到新數組的最後一個索引位置
        newArr[elements.length] =element;
        //將原先數組的指針指向新的數組
        elements = newArr;
    }

    //出隊(因爲是先進先出,所以出隊出的是第一個數據)
    public int poll(){
        //定義一個變量存儲第一個數據
        int element = elements[0];
        //首先需要判斷隊列裏面是不是有數據
        if(elements.length==0){
            throw new RuntimeException("The Queue is Empty!");
        }
        //創建一個數組用於存儲出隊後的數據
        int[] newArr=new int[elements.length-1];
        //將原先數組遍歷,並且賦值給到新的數組
        for (int i=0;i<elements.length-1;i++){
            newArr[i]=elements[i+1];
        }
        //將原來數組的指針指向新的數組
        elements = newArr;
        return element;
    }

}

測試類

class Test{
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.add(18);
        myQueue.add(90);
        myQueue.add(10);
        System.out.println(Arrays.toString(myQueue.elements) );
        System.out.println(myQueue.poll());
        myQueue.add(100);
        System.out.println(myQueue.poll());
        System.out.println(Arrays.toString(myQueue.elements) );
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章