其他分享
首页 > 其他分享> > [剑指Offer]-用两个队列实现栈

[剑指Offer]-用两个队列实现栈

作者:互联网

题目描述

用两个队列实现一个栈。

解题思路

算法图解

在这里插入图片描述

参考代码:
package offer;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 两个队列实现栈  先入后出
 */
public class Offer9_2 {
    static Queue<String> queue1 = new LinkedBlockingQueue<String>();
    static Queue<String> queue2 = new LinkedBlockingQueue<String>();

    public static void main(String[] args) {
        queue1.offer("xl");
        queue1.offer("xa");
        queue1.offer("xb");
        queue1.offer("xc");
        queue1.offer("xd");
        System.out.println(Offer9_2.deleteHead());
        System.out.println(Offer9_2.deleteHead());
        System.out.println(Offer9_2.deleteHead());
        System.out.println(Offer9_2.deleteHead());

    }

    private static String deleteHead() {
        if (queue2.isEmpty()) {
            int count = queue1.size();
            for (int i = 0; i < count - 1; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        } else {
            int count = queue2.size();
            for (int i = 0; i < count - 1; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }


    }
}


附录

该题源码在我的

标签:deleteHead,queue1,offer,队列,Offer,queue2,实现,Offer9
来源: https://blog.csdn.net/u011583316/article/details/89847637