前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:225. Implement Stack using Queues

LeetCode笔记:225. Implement Stack using Queues

作者头像
Cloudox
发布2021-11-23 14:53:37
1730
发布2021-11-23 14:53:37
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

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):

代码语言:javascript
复制
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

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档