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.

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false

Notes:

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

这个题目可以用两个stack, 基本思路是如@elmirap提出来的Solution, 两种方式, 第一种是O(n) push, 其他都是O(1)

Code:

class MyQueue(object):
##Solution
# two stacks, O(n) push operation def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
self.backup = [] def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
while self.stack:
self.backup.append(self.stack.pop())
self.stack.append(x)
while self.backup:
self.stack.append(self.backup.pop()) def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
return self.stack.pop() def peek(self):
"""
Get the front element.
:rtype: int
"""
return self.stack[-1] def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return not self.stack # Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

第二种方式, 平均pop为O(1), 其他都为O(1), 思路实际上类似, 但是在Stack2不急着将其搬回stack1, 因为在stack1搬到stack2之后已经将最后的放在最下面了.所以节约了时间.

Code:

class MyQueue:

    def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
self.queue = [] def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.stack.append(x) def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if not self.queue:
while self.stack:
self.queue.append(self.stack.pop())
return self.queue.pop() def peek(self):
"""
Get the front element.
:rtype: int
"""
return self.queue[-1] if self.queue else self.stack[0] def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return not self.stack and not self.queue # Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

[LeetCode] 232. Implement Queue using Stacks_Easy tag: Design的更多相关文章

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

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

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

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

  3. (easy)LeetCode 232.Implement Queue using Stacks

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

  4. Java [Leetcode 232]Implement Queue using Stacks

    题目描述: Implement the following operations of a queue using stacks. push(x) -- Push element x to the b ...

  5. LeetCode 232 Implement Queue using Stacks

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

  6. [LeetCode] 225. Implement Stack using Queues_Easy tag: Design

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

  7. Java for LeetCode 232 Implement Queue using Stacks

    Stack<Integer> stack=new Stack<Integer>(); public void push(int x) { stack.push(x); } // ...

  8. Leetcode 232 Implement Queue using Stacks STL

    本题用两个栈实现队列,用栈的基本操作去实现队列的所有基本操作push(),pop(),peek()以及empty() sa作为输入栈,sb作为输出栈,将sa输入元素的反转过来放到sb中 push与sa ...

  9. LeetCode 232 Implement Queue using Stacks 两个栈实现队列

    class MyQueue { public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x ...

随机推荐

  1. Elasticsearch学习之ElasticSearch 5.0.0 安装部署常见错误或问题

    ElasticSearch 5.0.0 安装部署常见错误或问题 问题一: [--06T16::,][WARN ][o.e.b.JNANatives ] unable to install syscal ...

  2. 下载Google Play外国区APP技巧

    安卓用户若遇到喜欢的APP是外国区的,只要FQ就能下载.比起果粉还要注册,是简便很多.但有没有更简单的办法?这个必须有!笔者前几天在网上闲逛时,就发现了一个给力的网站.让你不用FQ,只需3个步骤,就能 ...

  3. 使用eclipse执行maven-release-plugin插件发布jar异常问题(.project)(Cannot prepare the release because you have local modifications )

    开发是用的eclipse,里面有工程文件.project这种文件,运行release:prepare的时候报异常: Cannot prepare the release because you hav ...

  4. 【咸鱼教程】DragonBones帧动画、骨骼json、极速、二进制

    公司的人想用龙骨,但是同事在官网找不着二进制的资料...于是写了个简单demo. demo中包含了帧动画.骨骼动画json.极速和二进制的资源和代码 测试环境:DragonBonesPro 5.5  ...

  5. STS没有找到Dynamic Web Project

    解决:安装JavaEE插件 help-> install new software-> 选择sts对应的eclipse版本站点,如eclipse版本4.09选择2018-09.4.10选择 ...

  6. Linux下识别所有Android设备的方法

    修改/etc/udev/rules.d/51-android.rules文件. 方法一: 参考Google文档 SUBSYSTEM=="usb", ATTR{idVendor}== ...

  7. python pandas 豆瓣电影 top250 数据分析

    豆瓣电影top250数据分析 数据来源(豆瓣电影top250) 爬虫代码比较简单 数据较为真实,可以进行初步的数据分析 可以将前面的几篇文章中的介绍的数据预处理的方法进行实践 最后用matplotli ...

  8. ICSharpCode.SharpZipLib.dll 压缩多文件

    网站:http://icsharpcode.github.io/SharpZipLib/ 引用:ICSharpCode.SharpZipLib.dll private string CompassZi ...

  9. 洛谷P2178 品酒大会【后缀数组】【单调栈】

    题目描述 一年一度的“幻影阁夏日品酒大会”隆重开幕了.大会包含品尝和趣味挑战 两个环节,分别向优胜者颁发“首席品酒家”和“首席猎手”两个奖项,吸引了众多品酒师参加. 在大会的晚餐上,调酒师 Rainb ...

  10. Python排列函数:sort、sorted

    排序函数介绍:sort()和sorted()都属于Python list的排序方法 区别:sort()属于永久性排列,直接改变该list: sorted属于暂时性排列,会产生一个新的序列. #sort ...