494. 双队列实现栈

描述

利用两个队列来实现一个栈的功能

样例

push(1)
pop()
push(2)
isEmpty() // return false
top() // return 2
pop()
isEmpty() // return true

思路

一个 queue 用来存所有 push 进来的元素,另一个 queue 用来辅助,在要 top() 或者 pop() 的时候,因为要读取队尾的元素,可以将 queue1 中的元素弹出到只剩一个元素,弹出的元素由 queue2 接收,因为 queue 是先进先出,所以 queue2 中的元素顺序跟原先 queue1 中的元素顺序相同,
这之后 queue1 中剩下的那个元素就是需要的栈顶元素。如果是 top 方法那么只是读取这个元素,所以弹出之后再 offer 回来就可以了。

代码

class Stack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;
    
    public Stack() {
        queue1 = new LinkedList<Integer>();
        queue2 = new LinkedList<Integer>();
    }
    
    private void moveItems() {
        while (queue1.size() != 1) {
            queue2.offer(queue1.poll());
        }
    }
    // O(1) 的时间操作;
    private void swapQueues() {
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }
    
    /**
     * push a new item into the stack
     */
    public void push(int value) {
        queue1.offer(value);
    }
    
    /**
     * return the top of the stack
     */
    public int top() {
        moveItems();
        int item = queue1.poll();
        swapQueues();
        // 把元素重新添加到队列中去,保持原样,因为 top 不改变栈中的值
        // 实际上就是先把 queue1 中元素移到 queue2 中去,然后交换两个队列
        // queue1 变成 queue2,queue2 变成 queue1
        queue1.offer(item);
        return item;
    }
    
    /**
     * pop the top of the stack and return it
     */
    public void pop() {
        moveItems();
        queue1.poll();
        swapQueues();
    }
    
    /**
     * check the stack is empty or not.
     */
    public boolean isEmpty() {
        return queue1.isEmpty();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 3.10 69.给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问) 二叉树的层次遍历样例给一棵二叉树 {3...
    mytac阅读 4,758评论 3 3
  • 生活大爆炸版石头剪刀布 题目描述 石头剪刀布是常见的猜拳游戏:石头胜剪刀,剪刀胜布,布胜石头。如果两个人出拳一样,...
    bbqub阅读 3,332评论 0 0
  • 题目: 正如标题所述,你需要使用两个栈来实现队列的一些操作。队列应支持push(element),pop() 和 ...
    6默默Welsh阅读 1,488评论 0 0
  • 题目1: 用数组结构实现大小固定的栈 思路: 栈:栈是后进先出的,所以定义一个变量size用来记数组下标,入栈就是...
    一凡呀阅读 2,962评论 0 0
  • 数组索引 这样声明个数组,名为radius,含3个int型元素。我们可通过radius[0],radius[1],...
    夏威夷的芒果阅读 4,503评论 1 0