LeetCode 225. 用队列实现栈

我的思路:用两个队列实现栈,那肯定需要一个队列作为辅助队列。我用了两个队列queue1,queue2,其中queue2是给queue1打辅助的,不像用两个栈实现一个队列的思路解决这个问题,因为队列是先进先出的。把queue1的元素全部入队到queue2中,元素的出顺序是没有变化的。我是在出栈处上做文章,而leetcode官方题解是在入栈处做文章。入栈时直接入队到queue1中,出栈时queue1队尾的元素就是栈顶元素,我们需要获得它,直接将queue1队尾之前的元素全部入队到queue2,取得它,再把queue2的元素全部入队到queue1中。

class MyStack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        queue1.add(x);
    }

    public int pop() {
        while (queue1.size() > 1) {
            queue2.add(queue1.poll());
        }
        int res = queue1.poll();
        while (!queue2.isEmpty()) {
            queue1.add(queue2.poll());
        }
        return res;
    }

    public int top() {
        while (queue1.size() > 1) {
            queue2.add(queue1.poll());
        }
        int res = queue1.poll();
        queue2.add(res);
        while (!queue2.isEmpty()) {
            queue1.add(queue2.poll());
        }
        return res;
    }

    public boolean empty() {
        return queue1.isEmpty();
    }
}

leetcode官方题解的两种思路:一种用了两个队列queue1(作为真正的栈),queue2,入栈时元素e入队到queue2中,在把queue1的元素全部入队到queue2中,最后交换queue1、queue2,这样queue1队首的元素就是栈顶的元素,而queue2是空队。另一种用一个队列实现,就是在入栈时,把队列的队尾之前的元素再重新入队到这个队列。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值