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中的元素存回来,这样就是我们要的顺序了,其他三个操作也就直接调用栈的操作即可,参见代码如下:

解法一:

class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {} /** Push element x to the back of queue. */
void push(int x) {
stack<int> tmp;
while (!st.empty()) {
tmp.push(st.top()); st.pop();
}
st.push(x);
while (!tmp.empty()) {
st.push(tmp.top()); tmp.pop();
}
} /** Removes the element from in front of queue and returns that element. */
int pop() {
int val = st.top(); st.pop();
return val;
} /** Get the front element. */
int peek() {
return st.top();
} /** Returns whether the queue is empty. */
bool empty() {
return st.empty();
} private:
stack<int> st;
};

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

解法二:

class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {} /** Push element x to the back of queue. */
void push(int x) {
_new.push(x);
} /** Removes the element from in front of queue and returns that element. */
int pop() {
shiftStack();
int val = _old.top(); _old.pop();
return val;
} /** Get the front element. */
int peek() {
shiftStack();
return _old.top();
} /** Returns whether the queue is empty. */
bool empty() {
return _old.empty() && _new.empty();
} void shiftStack() {
if (!_old.empty()) return;
while (!_new.empty()) {
_old.push(_new.top());
_new.pop();
}
} private:
stack<int> _old, _new;
};

类似题目:

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. ASP.NET Core 中文文档 第三章 原理(10)依赖注入

    原文:Dependency Injection 作者:Steve Smith 翻译:刘浩杨 校对:许登洋(Seay).高嵩 ASP.NET Core 的底层设计支持和使用依赖注入.ASP.NET Co ...

  2. ASP.NET Core 中文文档 第三章 原理(12)托管

    原文:Hosting 作者:Steve Smith 翻译:娄宇(Lyrics) 校对:何镇汐.许登洋(Seay) 为了运行 ASP.NET Core 应用程序,你需要使用 WebHostBuilder ...

  3. Bloom Filter:海量数据的HashSet

    Bloom Filter一般用于数据的去重计算,近似于HashSet的功能:但是不同于Bitmap(用于精确计算),其为一种估算的数据结构,存在误判(false positive)的情况. 1. 基本 ...

  4. Django--自定义用户认证

    Django自带的用户认证 以前都是用Django自带的用户认证,用户名字段一对一关系对应Django--User表(其实它也是继承了abstractbaseuser). 1 2 3 from dja ...

  5. iOS 调试工具

    仪表  xcode5 引入了调试仪表,通过仪表可以直观的看出应用的CPU和内存占用量.运行一个程序,点击仪表栏.可以发现当程序处于运行状态时,调试导航面板会以柱状图显示CPU和内存占用量,并随着应用实 ...

  6. PyQt4入门学习笔记(五)

    PyQt4里的对话框 对话框是大多数GUI应用中不可分割的一部分.一个对话框是两者或多者的会话.在GUI内,对话框是应用向人说话的方式.一个对话框可以用来输入数据,修改数据,改变应用设置等等. QtG ...

  7. WinForm拖动没有标题栏窗体的方法

    建立窗体的名称修改为:Form_HoverTree 文后附有源码下载. 主要代码: Point _HoverTreePosition; public Form_HoverTree() { Initia ...

  8. java.net.SocketException: Connection reset

    java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java ...

  9. bootstrap杂记

    http://v3.bootcss.com/ 这个国内的中文站点资料很全 如下看个页面的大体框架 http://www.cnblogs.com/sunhaoyu/p/4275190.html < ...

  10. Laravel大型项目系列教程(一)

    Laravel大型项目系列教程(一) 一.课程概述 1.课程介绍 本教程将使用Laravel完成一个多用户的博客系统,大概会包含如下内容: 路由管理. 用户管理,如用户注册.修改信息.锁定用户等. 文 ...