Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

这道题让我们用栈来实现队列,之前我们做过一道相反的题目Implement Stack using Queues 用队列来实现栈,是用队列来实现栈。这道题颠倒了个顺序,起始并没有太大的区别,栈和队列的核心不同点就是栈是先进后出,而队列是先进先出,那么我们要用栈的先进后出的特性来模拟出队列的先进先出。那么怎么做呢,其实很简单,只要我们在插入元素的时候每次都都从前面插入即可,比如如果一个队列是1,2,3,4,那么我们在栈中保存为4,3,2,1,那么返回栈顶元素1,也就是队列的首元素,则问题迎刃而解。所以此题的难度是push函数,我们需要一个辅助栈tmp,把s的元素也逆着顺序存入tmp中,此时加入新元素x,再把tmp中的元素存回来,这样就是我们要的顺序了,其他三个操作也就直接调用栈的操作即可,参见代码如下:

解法一:

  1. class MyQueue {
  2. public:
  3. /** Initialize your data structure here. */
  4. MyQueue() {}
  5.  
  6. /** Push element x to the back of queue. */
  7. void push(int x) {
  8. stack<int> tmp;
  9. while (!st.empty()) {
  10. tmp.push(st.top()); st.pop();
  11. }
  12. st.push(x);
  13. while (!tmp.empty()) {
  14. st.push(tmp.top()); tmp.pop();
  15. }
  16. }
  17.  
  18. /** Removes the element from in front of queue and returns that element. */
  19. int pop() {
  20. int val = st.top(); st.pop();
  21. return val;
  22. }
  23.  
  24. /** Get the front element. */
  25. int peek() {
  26. return st.top();
  27. }
  28.  
  29. /** Returns whether the queue is empty. */
  30. bool empty() {
  31. return st.empty();
  32. }
  33.  
  34. private:
  35. stack<int> st;
  36. };

上面那个解法虽然简单,但是效率不高,因为每次在push的时候,都要翻转两边栈,下面这个方法使用了两个栈_new和_old,其中新进栈的都先缓存在_new中,入股要pop和peek的时候,才将_new中所有元素移到_old中操作,提高了效率,代码如下:

解法二:

  1. class MyQueue {
  2. public:
  3. /** Initialize your data structure here. */
  4. MyQueue() {}
  5.  
  6. /** Push element x to the back of queue. */
  7. void push(int x) {
  8. _new.push(x);
  9. }
  10.  
  11. /** Removes the element from in front of queue and returns that element. */
  12. int pop() {
  13. shiftStack();
  14. int val = _old.top(); _old.pop();
  15. return val;
  16. }
  17.  
  18. /** Get the front element. */
  19. int peek() {
  20. shiftStack();
  21. return _old.top();
  22. }
  23.  
  24. /** Returns whether the queue is empty. */
  25. bool empty() {
  26. return _old.empty() && _new.empty();
  27. }
  28.  
  29. void shiftStack() {
  30. if (!_old.empty()) return;
  31. while (!_new.empty()) {
  32. _old.push(_new.top());
  33. _new.pop();
  34. }
  35. }
  36.  
  37. private:
  38. stack<int> _old, _new;
  39. };

类似题目:

Implement Stack using Queues

参考资料:

https://leetcode.com/problems/implement-queue-using-stacks/

https://leetcode.com/problems/implement-queue-using-stacks/discuss/64197/Easy-Java-solution-just-edit-push()-method

https://leetcode.com/problems/implement-queue-using-stacks/discuss/64206/Short-O(1)-amortized-C%2B%2B-Java-Ruby

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Implement Queue using Stacks 用栈来实现队列的更多相关文章

  1. [LeetCode] 232. Implement Queue using Stacks 用栈来实现队列

    Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...

  2. 232 Implement Queue using Stacks 用栈来实现队列

    使用栈来实现队列的如下操作: push(x) -- 将一个元素放入队列的尾部.pop() -- 从队列首部移除元素.peek() -- 返回队列首部的元素.empty() -- 返回队列是否为空.注意 ...

  3. Leetcode Implement Queue using Stacks

    Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...

  4. LeetCode——Implement Queue using Stacks

    Description: Implement the following operations of a queue using stacks. push(x) -- Push element x t ...

  5. LeetCode Implement Queue using Stacks (数据结构)

    题意: 用栈来实现队列. 思路: 一个栈是不够的,至少要两个. (1)插入.永远只插入到stack1中(插到栈顶). (2)弹出.如果stack2不为空,直接弹出stack2的栈顶,否则,将stack ...

  6. LeetCode OJ:Implement Queue using Stacks(栈实现队列)

    比较典型的一个题目,easy,不过可以有许多实现方式. 这里用的方式是每次pop完成之后再将stack2中的内容立即倒回stack1中.但是其他的实现也可以不是这样,可以是需要push的时候检查再,如 ...

  7. LeetCode 232. 用栈实现队列(Implement Queue using Stacks) 4

    232. 用栈实现队列 232. Implement Queue using Stacks 题目描述 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部. pop() -- 从 ...

  8. leetcode:Implement Stack using Queues 与 Implement Queue using Stacks

    一.Implement Stack using Queues Implement the following operations of a stack using queues. push(x) - ...

  9. Leetcode 232 Implement Queue using Stacks 和 231 Power of Two

    1. 232 Implement Queue using Stacks 1.1 问题描写叙述 使用栈模拟实现队列.模拟实现例如以下操作: push(x). 将元素x放入队尾. pop(). 移除队首元 ...

随机推荐

  1. 你真的会玩SQL吗?和平大使 内连接、外连接

    你真的会玩SQL吗?系列目录 你真的会玩SQL吗?之逻辑查询处理阶段 你真的会玩SQL吗?和平大使 内连接.外连接 你真的会玩SQL吗?三范式.数据完整性 你真的会玩SQL吗?查询指定节点及其所有父节 ...

  2. Wizard Framework:一个自己开发的基于Windows Forms的向导开发框架

    最近因项目需要,我自己设计开发了一个基于Windows Forms的向导开发框架,目前我已经将其开源,并发布了一个NuGet安装包.比较囧的一件事是,当我发布了NuGet安装包以后,发现原来已经有一个 ...

  3. .NET 垃圾回收与内存泄漏

    > 前言相信大家一定听过,看过甚至遇到过内存泄漏.在 .NET 平台也一定知道有垃圾回收器,它可以让开发人员不必担心内存的释放问题,因为它会自定管理内存.但是在 .NET 平台下进行编程,绝对不 ...

  4. Checkbox 模板和样式

    <Style TargetType="{x:Type CheckBox}"> <Setter Property="FontFamily" Va ...

  5. 深入Collection集合

    List集合 一.ArraryList: 最基本的集合不多做介绍 二.Vector Vector cn=new  Vector(); A:有特有功能 a:添加       public void ad ...

  6. 记录一次bug解决过程:else未补全导致数据泄露和代码优化

    一.总结 快捷键ctrl + alt + 四个方向键 --> 倒置屏幕 未补全else逻辑,倒置查询数据泄露 空指针是最容易犯的错误,数据的空指针,可以普遍采用三目运算符来解决 SVN冲突解决关 ...

  7. Java01

    1.JAVA历史概述       百度百科:http://baike.baidu.com/view/29.htm      詹姆斯.高斯林  (高司令)----java之父    Sun Micros ...

  8. SharePoint文档库文件夹特殊字符转义

    当我们在SharePoint网站文档库中新建文件夹时包含了~ " # % & * : < > ? / \ { | }字符时(一共15个), 或者以.开头或者结束,或者包含 ...

  9. React-Native坑:Invariant Violation:Application 项目名 has not been registered.

    前言 在学习一门新技术的你也许有跟我一样的困惑,照着书上或者视频上的敲了.但是就是有各种问题没有出来自己想要的结果.我会将自己在这个过程中遇到的坑都记录下来,不一定全覆盖,但希望这些文章可以解决你的问 ...

  10. 解析Jquery取得iframe中元素的几种方法

    iframe在复合文档中经常用到,利用jquery操作iframe可以大幅提高效率,这里收集一些基本操作,需要的朋友可以参考下   DOM方法:父窗口操作IFRAME:window.frames[&q ...