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. Qt+imx6编写的楼宇对讲管理平台

    第一个初步版本. 1:楼宇对讲模块.住户报警模块.门禁控制模块.系统设置模块. 2:实时对讲信息卡片式展示,通话记录表格展示. 3:设备面板展示,实时显示上下线报警等信息. 4:设备查询.记录查询.运 ...

  2. makefile高级应用

    https://www.zybuluo.com/lishuhuakai/note/206938 make是Linux下的一款程序自动维护工具,配合makefile的使用,就能够根据程序中模块的修改情况 ...

  3. laravel blade模板里调用路由方法重定向

    @if (Session::get('user') == NULL) {!!Redirect::to('login')!!} @endif or @if (Session::get('user') = ...

  4. 遍历json数组实现树

    今天小颖在工作中遇到要遍历树得问题了,实现后,怕后期遇到又忘记啦,所以记录下嘻嘻,其实这个和小颖之前写过得一篇文章    json的那些事    中第4点有关json的面试题有些类似. 数组格式: v ...

  5. mint下截图工具shutter的安装和使用设置

    [原创作品,技术交流.允许转载,转载时请务必以超链接形式标明文章原始出处 .作者信息.如有错误,请指正] /** author: lihaibo date: 1/25/2016 */ 今天安装了双系统 ...

  6. 【黑金原创教程】【FPGA那些事儿-驱动篇I 】实验十八:SDRAM模块① — 单字读写

    实验十八:SDRAM模块① — 单字读写 笔者与SDRAM有段不短的孽缘,它作为冤魂日夜不断纠缠笔者.笔者尝试过许多方法将其退散,不过屡试屡败的笔者,最终心情像橘子一样橙.<整合篇>之际, ...

  7. IIS7配置伪静态把后缀名映射为html方案

    1.在IIS新建站点.[创建的时候不用去选择版本和模式,默认即可] 2.选中站点,切换到功能试图,找到“处理程序映射",双击之后,在打开窗口右侧的操作栏目下做如下设置: 1)右边" ...

  8. iOS 面试题整理(带答案)二

    第一篇面试题整理: http://www.cocoachina.com/bbs/read.php?tid-459620.html 本篇面试题同样:如答案有问题,欢迎指正! 1.回答person的ret ...

  9. 【Android】 导入项目报错的解决方案

    1.打项目的properties -->android 为其指一个运版本, 2.修改default properties 文件 ,改相应版本等级 3.选中项目,单击右键,选中properties ...

  10. HTML中块级元素与内联元素有什么区别 ?

    块级元素:默认宽度是100%(继承自父元素),如果块对象没有采用“float:left”或“float:right;”的样式,相邻的两个块对象就会分排在不同的两行上.例如,div, p, h1, fo ...