队列进出原则

    /**
     * 队列存取元素遵循先进先出原则
     * @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());
        }

    }



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值