用两个队列实现栈

2019-08-14  本文已影响0人  Tiramisu_b630

题目: 用两个队列模拟实现栈的push以及pop操作。

解法:

    /**
     * 两个栈实现队列只需要一个用做入栈操作,
     * 一个用做出栈操作,而两个队列实现栈需
     * 要两个队列交替使用,当一个队列有元素,
     * 要出栈就需要出该队列的最后一个元素,所
     * 以需要先把最后一个元素之外的元素,转到
     * 另一个队列。
     */
    private LinkedList<Integer> queue1=new LinkedList<>();
    private LinkedList<Integer> queue2=new LinkedList<>();
    private int pop(){
        if (queue1.isEmpty()&&queue2.isEmpty()){
            return -1;
        }else if (queue1.isEmpty()){
            while (queue2.size()>1){
                queue1.push(queue2.pollLast());
            }
            return queue2.pollLast();
        }else if (queue2.isEmpty()){
            while (queue1.size()>1){
                queue2.push(queue1.pollLast());
            }
            return queue1.pollLast();
        }
        return -1;
    }
    /**
     *队列1不为空,入栈时进队列1,否则进队列2
     * @param x
     */
    private void push(int x){
        if (!queue1.isEmpty()){
            queue1.push(x);
        }else {
            queue2.push(x);
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读