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.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false

Notes:

  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, 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).

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

这道题让我们用队列来实现栈,队列和栈作为两种很重要的数据结构,它们最显著的区别就是,队列是先进先出,而栈是先进后出。题目要求中又给定了限制条件只能用 queue 的最基本的操作,像 back() 这样的操作是禁止使用的。那么怎么样才能让先进先出的特性模拟出先进后出呢,这里就需要另外一个队列来辅助操作,我们总共需要两个队列,其中一个队列用来放最后加进来的数,模拟栈顶元素。剩下所有的数都按顺序放入另一个队列中。当 push() 操作时,将新数字先加入模拟栈顶元素的队列中,如果此时队列中有数字,则将原本有的数字放入另一个队中,让新数字在这队中,用来模拟栈顶元素。当 top() 操作时,如果模拟栈顶的队中有数字则直接返回,如果没有则到另一个队列中通过平移数字取出最后一个数字加入模拟栈顶的队列中。当 pop() 操作时,先执行下 top() 操作,保证模拟栈顶的队列中有数字,然后再将该数字移除即可。当 empty() 操作时,当两个队列都为空时,栈为空。代码如下:

解法一:

class MyStack {
public:
MyStack() {}
void push(int x) {
q2.push(x);
while (q2.size() > ) {
q1.push(q2.front()); q2.pop();
}
}
int pop() {
int x = top(); q2.pop();
return x;
}
int top() {
if (q2.empty()) {
for (int i = ; i < (int)q1.size() - ; ++i) {
q1.push(q1.front()); q1.pop();
}
q2.push(q1.front()); q1.pop();
}
return q2.front();
}
bool empty() {
return q1.empty() && q2.empty();
}
private:
queue<int> q1, q2;
};

这道题还有另一种解法,可以参见另一道类似的题 Implement Queue using Stacks,我个人来讲比较偏爱下面这种方法,比较好记,只要实现对了 push() 函数,后面三个直接调用队列的函数即可。这种方法的原理就是每次把新加入的数插到前头,这样队列保存的顺序和栈的顺序是相反的,它们的取出方式也是反的,那么反反得正,就是我们需要的顺序了。我们可以使用一个辅助队列,把q的元素也逆着顺序存入到辅助队列中,此时加入新元素x,再把辅助队列中的元素存回来,这样就是我们要的顺序了。当然,我们也可以直接对队列q操作,在队尾加入了新元素x后,将x前面所有的元素都按顺序取出并加到队列到末尾,这样下次就能直接取出x了,符合栈到后入先出到特性,其他三个操作也就直接调用队列的操作即可,参见代码如下:

解法二:

class MyStack {
public:
MyStack() {}
void push(int x) {
q.push(x);
for (int i = ; i < (int)q.size() - ; ++i) {
q.push(q.front()); q.pop();
}
}
int pop() {
int x = q.front(); q.pop();
return x;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
};

讨论:上面两种解法对于不同的输入效果不同,解法一花在 top() 函数上的时间多,所以适合于有大量 push() 操作,而 top() 和 pop() 比较少的输入。而第二种解法在 push() 上要花大量的时间,所以适合高频率的 top() 和 pop(),较少的 push()。两种方法各有千秋,互有利弊。

类似题目:

Implement Queue using Stacks

参考资料:

https://leetcode.com/problems/implement-stack-using-queues/

https://leetcode.com/problems/implement-stack-using-queues/discuss/62527/A-simple-C%2B%2B-solution

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

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

  1. [LeetCode] 225. Implement Stack using Queues 用队列来实现栈

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  2. LeetCode OJ:Implement Stack using Queues(队列实现栈)

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  3. (leetcode)Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  4. LeetCode——Implement Stack using Queues

    Description: Implement the following operations of a stack using queues. push(x) -- Push element x o ...

  5. Implement Stack using Queues 用队列实现栈

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  6. LeetCode Implement Stack using Queues (数据结构)

    题意: 用队列来实现栈. 思路: 没有什么捷径,纯粹模拟.但是用一个队列就够了. class Stack { /* // Push element x onto stack. void push(in ...

  7. LeetCode 225 Implement Stack using Queues 用队列实现栈

    1.两个队列实现,始终保持一个队列为空即可 class MyStack { public: /** Initialize your data structure here. */ MyStack() ...

  8. 225 Implement Stack using Queues(用队列实现栈Medium)

    题目意思:用队列实现栈,push(),pop(),top(),empty() 思路:用两个queue,pop时将一个queue的元素pop再push到另一个队列,queue只留最后一个元素,并pop, ...

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

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

随机推荐

  1. 读书笔记--SQL必知必会17--创建和操纵表

    17.1 创建表 使用CREATE TABLE语句创建表. 不同的DBMS中CREATE TABLE语句的语法可能不同. 17.1.1 表创建基础 利用CREATE TABLE创建表,必须具备如下信息 ...

  2. SpingMVC 核心技术帮助文档

    声明:本篇文档主要是用于参考帮助文档,没有实例,但几乎包含了SpringMVC 4.2版本的所有核心技术,当前最新版本是4.3,4.2的版本已经经是很新的了,所以非常值得大家一读,对于读完这篇文档感觉 ...

  3. 利用Python进行数据分析(1) 简单介绍

    一.处理数据的基本内容 数据分析 是指对数据进行控制.处理.整理.分析的过程. 在这里,“数据”是指结构化的数据,例如:记录.多维数组.Excel 里的数据.关系型数据库中的数据.数据表等. 二.说说 ...

  4. JWT实现token-based会话管理

    上文<3种web会话管理的方式>介绍了3种会话管理的方式,其中token-based的方式有必要从实现层面了解一下.本文主要介绍这方面的内容.上文提到token-based的实现目前有一个 ...

  5. .NET之全平台一体化的体验

    一.前言 近来利用空闲时间研究了一下Xamarin的技术,想想既然提供了如此好的支持,就该尝试一切可能,来一个”大小通吃“. 何为全平台:APP包括Android.IOS.WP,WEB可在Window ...

  6. 基于CkEditor实现.net在线开发之路(7)列表页面开发动作介绍

    一个列表页面不止是查询,它也包含了很多业务上功能的实现,这些业务功能的实现的逻辑我称之为动作.如触发单击按钮删除数据,更改业务表数据,调用webService,调用WCF接口,弹出新窗体新增.修改.查 ...

  7. Web测试介绍2一 安全测试

            安全测试是在IT软件产品的生命周期中,特别是产品开发基本完成到发布阶段,对产品进行检验以验证产品符合安全需求定义和产品质量标准的过程. 主要安全需求包括: (i) 认证 Authent ...

  8. DbMigration使用方法

    1.Enable-Migrations -ContextTypeNameLITCS.Data.gmisContext Enable-Migrations  命令创建了一个新的Migrations文件夹 ...

  9. CSS3鼠标滑过动画线条边框特效

    基于CSS属性animation动画制作,效果流畅弹性十足 效果展示 http://hovertree.com/texiao/css3/32/ 源码下载:http://hovertree.com/h/ ...

  10. swing with transformjs

    Antecedent Facebook made a HTML5 game long time ago. The opening animation is a piece of software th ...