Leetcode225. Implement Stack using Queues

该题和232题类似,思想上差不多232题
原题
Implement the following operations of a stack using queues.

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
empty() – Return whether the stack is empty.
Notes:
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
翻译
使用队列实现堆栈的以下操作。
push(x) - 将元素x推入堆栈。
pop() - 删除堆栈顶部的元素。
top() - 获取顶层元素。
empty() - 返回堆栈是否为空。

您必须只使用队列的标准操作 - 这意味着从前面看/弹出,大小和空操作都有效。
根据您的语言,队列可能不支持本机。 您可以使用列表或deque(双端队列)模拟队列,只要只使用队列的标准操作即可。
您可以假定所有操作都是有效的(例如,不会在空堆栈上调用pop或top操作)。
思路
使用两个队列来完成一个栈,把队列的元素移到另一个队列,直到还剩最后一个;这个元素即为栈顶的元素。
代码

class MyStack {
   private Queue<Integer>queue1=new LinkedList<>();
    private Queue<Integer>queue2=new LinkedList<>();
    // Push element x onto stack.添加元素至栈中
    public void push(int x) {
        queue1.offer(x);

    }

    // Removes the element on top of the stack.从栈顶移除元素
    public void pop() {
        if (queue1.size()==0) {
            return;

        }
        //逐个把队1的元素移动到队中,直至剩一个元素,则为栈顶的元素

        while(queue1.size()>1)
            queue2.offer(queue1.poll());
        queue1.poll();
            //注意先把队2中元素复制到队1中,然后再将队2元素置为空
        Queue<Integer>q=queue2;
        queue2=queue1;
        queue1=q;
    }

    // Get the top element.
    //返回栈顶的元素
    public int top() {
        if (queue1.size()==0) {
            return 0;

        }
        //将队1中元素移到队2中,然后剩下最后一个,就是栈顶元素
        while(queue1.size()>1)
            queue2.offer(queue1.poll());
       int temp= queue1.poll();
       //把最后一个抛出去的元素加进队列2中,然后队1和队2的元素互换
      queue2.offer(temp);
        Queue<Integer>q=queue2;
        queue2=queue1;
        queue1=q;
        return temp;

    }

    // Return whether the stack is empty.
    public boolean empty() {
        return queue1.isEmpty();

    }
}
[原题链接](https://leetcode.com/problems/implement-stack-using-queues/)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值