隊列進出原則

    /**
     * 隊列存取元素遵循先進先出原則
     * @author Heying_He
     *
     */

    public static void main(String[] args) {
        firstQueue();
        System.out.println("**************FUN2*****************");
        pollQueue();
    }

    /**
     * poll() 從隊首移除並返回該元素 出隊<br>
     * peek() 引用隊首元素,該操作不會將隊首元素移除
     */
    public static void firstQueue(){
        Queue<String> queue = new LinkedList<String>();

        queue.add("A");
        queue.add("B");
        queue.add("C");
        System.out.println(queue);

        /*
         * 從隊首移除並返回該元素  出隊
         * poll
         */
        String e = queue.poll();
        System.out.println("隊首是>> "+e);
        System.out.println(queue);

        /*
         * peek()方法:
         * 引用隊首元素,該操作不會將隊首元素移除
         */
        e = queue.peek();
        System.out.println("peek 之後的隊首是>> "+e);
        System.out.println(queue);
    }

    public static void pollQueue(){
        Queue<String> queue = new LinkedList<String>();

        queue.add("1");
        queue.add("2");
        queue.add("3");

        System.out.println(queue);
        // peek
        for (int i = queue.size(); i > 0; i-- ) { // 每次poll隊列數量都會減少,要用減法
            System.out.println(queue.peek());
        }
        System.out.println("#####>> peek over");
        // 1
        for (int i = queue.size(); i > 0; i-- ) { // 每次poll隊列數量都會減少,要用減法
            System.out.println(queue.poll());
        }
        // 2 遍歷
        System.out.println("###########>> poll over");
        queue.add("1");
        queue.add("2");
        queue.add("3");
        for (String queuer : queue) {
            System.out.println(queuer);
        }
        // 3
        System.out.println("###########");
        while(queue.size() > 0){ // ***當隊列爲空時,poll方法返回null***
            System.out.println(queue.poll());
        }

    }



發佈了63 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章