[LeetCode] 232. Implement Queue using Stacks_Easy tag: Design
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 top,peek/pop from top,size, andis emptyoperations 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的更多相关文章
- Leetcode 232 Implement Queue using Stacks 和 231 Power of Two
1. 232 Implement Queue using Stacks 1.1 问题描写叙述 使用栈模拟实现队列.模拟实现例如以下操作: push(x). 将元素x放入队尾. pop(). 移除队首元 ...
- [LeetCode] 232. Implement Queue using Stacks 用栈来实现队列
Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...
- (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 ...
- Java [Leetcode 232]Implement Queue using Stacks
题目描述: Implement the following operations of a queue using stacks. push(x) -- Push element x to the b ...
- LeetCode 232 Implement Queue using Stacks
Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...
- [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 ...
- Java for LeetCode 232 Implement Queue using Stacks
Stack<Integer> stack=new Stack<Integer>(); public void push(int x) { stack.push(x); } // ...
- Leetcode 232 Implement Queue using Stacks STL
本题用两个栈实现队列,用栈的基本操作去实现队列的所有基本操作push(),pop(),peek()以及empty() sa作为输入栈,sb作为输出栈,将sa输入元素的反转过来放到sb中 push与sa ...
- LeetCode 232 Implement Queue using Stacks 两个栈实现队列
class MyQueue { public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x ...
随机推荐
- imsdroid 学习(初认识)
转:http://www.cnblogs.com/milospooner/archive/2012/07/15/2591979.html idoubs是imsdroid的IOS版本. 从google以 ...
- Android.mk (2) 函数进阶教程 - 分支、循环、子程序
https://www.jianshu.com/p/674dc7d7b4b0 函数进阶教程 - 分支.循环.子程序 按照面向过程程序设计的标准流程,我们讲完了顺序结构,就要讲分支.循环和子程序.下面我 ...
- Elasticsearch学习之基本核心概念
在Elasticsearch中有许多术语和概念 1. 核心概念 Elasticsearch集群可以包含多个索引(indices)(数据库),每一个索引可以包含多个类型(types)(表),每一个类型包 ...
- Windows平台编译SQLite 3
由于需要sqlite的x64版本只能自己编译,下载sqlite源代码.sqlite.def.Visual Studio 2013新建一个Visual C++ Empty Project,Configu ...
- 【JSP】JSP指令
JSP指令 说明: 1.JSP指令用于告知JSP 引擎转译JSP时的转化参数,他们不产生输出信息,只是在JSP的转译和编译期间起作用. 2.JSP指令必须写在规定的格式中: <%@ [go ...
- 【BZOJ3691】游行 费用流
[BZOJ3691]游行 Description 每年春季,在某岛屿上都会举行游行活动.在这个岛屿上有N个城市,M条连接着城市的有向道路.你要安排英雄们的巡游.英雄从城市si出发,经过若干个城市,到城 ...
- s3cmd在配置后使用时提示ERROR: S3 error: 403 (InvalidAccessKeyId): The AWS Access Key Id you provided does not exist in our records.
自己新建的ceph环境,下载了s3cmd来做客户端,使用了s3cmd --configure配置后,在使用s3cmd ls可以查看到所有的bucket,但s3cmd ls s3://xxx 具体buc ...
- 近期在看的一段JS(谁能看出我想实现什么功能)
示例代码: <script type="text/javascript"> !function(){ var e=/([http|https]:\/\/[a-zA-Z0 ...
- vue---进行post和get请求
参考文档: https://www.jb51.net/article/125717.htm 使用axios <script src="https://unpkg.com/axios/d ...
- 转Python SciPy库——拟合与插值
1.最小二乘拟合 实例1 import numpy as np import matplotlib.pyplot as plt from scipy.optimize import leastsq p ...