LeetCode笔记:225. Implement Stack using Queues

问题:

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)–将元素xpush到栈中去。
  • pop()–移除栈顶的元素。
  • top()–获取栈顶的元素。
  • empty()–返回栈是否为空。

注意:

  • 你只能使用队列的标准操作——也就是只有push到队尾、从队首peek/pop、size和是否为empty操作是有效的。
  • 根据你的语言,队列可能不是原生支持的。你可以使用list或者deque(双尾队列)模仿一个队列,只要你只使用队列的标准操作。
  • 你可以假设所有的操作都是有效的(比如,不会pop或者top一个空栈)。

思路:

这道题和232. Implement Queue using Stacks很像,跟他是相反的要求。

其实用队列实现栈无非就是一个出的顺序不一样,栈是后进先出,队列是先进先出,因此要么改变队列出的做法,全部出完直到最后一个才是作为栈需要出的;要么改入队的做法,每次入的时候都全部取出来一遍,将新元素入在队首去,这样出的时候就是第一个出的了。

因为题目的代码要求有两个取元素操作,一个添加元素操作,所以我采用了第二种做法,改变入队方式,具体实现还是很简单的。

代码(Java):

class MyStack {
    Queue<Integer> q;

    public MyStack(){
        q = new LinkedList<Integer>();
        //temp = new LinkedList<Integer>();
    }

    // Push element x onto stack.
    public void push(int x) {
        Queue<Integer> temp = new LinkedList<Integer>();
        while (q.peek() != null) {
            temp.add(q.poll());
        }
        q.add(x);
        while (temp.peek() != null) {
            q.add(temp.poll());
        }
    }

    // Removes the element on top of the stack.
    public void pop() {
        q.remove();
    }

    // Get the top element.
    public int top() {
        return q.peek();
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return q.peek() == null;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值