来源:https://leetcode.com/problems/implement-queue-using-stacks

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 toppeek/pop from topsize, and is 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).

栈A负责push,栈B负责pop和peek,当pop或peek时,如果栈B没有元素,就将栈A中的内容按栈的pop顺序push到栈B中

Java

 class MyQueue {
Stack<Integer> input;
Stack<Integer> output;
/** Initialize your data structure here. */
public MyQueue() {
input = new Stack<Integer>();
output = new Stack<Integer>();
} /** Push element x to the back of queue. */
public void push(int x) {
input.push(x);
} /** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
return output.pop();
} /** Get the front element. */
public int peek() {
if(output.empty()) {
int len = input.size();
for(int i=0; i<len; i++) {
output.push(input.pop());
}
}
return output.peek();
} /** Returns whether the queue is empty. */
public boolean empty() {
return input.empty() && output.empty();
}
} /**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/

Python

 class MyQueue(object):
i_stack = []
o_stack = []
def __init__(self):
"""
Initialize your data structure here.
"""
self.i_stack = []
self.o_stack = [] def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.i_stack.append(x) def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
self.peek()
return self.o_stack.pop() def peek(self):
"""
Get the front element.
:rtype: int
"""
if len(self.o_stack) == 0:
i_len = len(self.i_stack)
for i in range(i_len):
self.o_stack.append(self.i_stack.pop())
return self.o_stack[-1] def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return len(self.i_stack) == 0 and len(self.o_stack) == 0 # 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()

Implement Queue using Stacks(用两个栈实现队列)的更多相关文章

  1. LeetCode 232. 用栈实现队列(Implement Queue using Stacks) 4

    232. 用栈实现队列 232. Implement Queue using Stacks 题目描述 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部. pop() -- 从 ...

  2. [CareerCup] 3.5 Implement Queue using Two Stacks 使用两个栈来实现队列

    3.5 Implement a MyQueue class which implements a queue using two stacks. LeetCode上的原题,请参见我之前的博客Imple ...

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

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

  4. LeetCode 232 Implement Queue using Stacks

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

  5. Lintcode: Implement Queue by Stacks 解题报告

    Implement Queue by Stacks 原题链接 : http://lintcode.com/zh-cn/problem/implement-queue-by-stacks/# As th ...

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

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

  7. Leetcode 232 Implement Queue using Stacks STL

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

  8. 【LeetCode】232 & 225 - Implement Queue using Stacks & Implement Stack using Queues

    232 - Implement Queue using Stacks Implement the following operations of a queue using stacks. push( ...

  9. 232. Implement Queue using Stacks,225. Implement Stack using Queues

    232. Implement Queue using Stacks Total Accepted: 27024 Total Submissions: 79793 Difficulty: Easy Im ...

  10. leetcode 155. Min Stack 、232. Implement Queue using Stacks 、225. Implement Stack using Queues

    155. Min Stack class MinStack { public: /** initialize your data structure here. */ MinStack() { } v ...

随机推荐

  1. os.path.sep

    python中os.path常用模块 os.path.sep:路径分隔符      linux下就用这个了’/’ os.path.altsep: 根目录 os.path.curdir:当前目录 os. ...

  2. Linux 下安装中文字体

    本文以安装黑体为例,简单演示如何在Linux下安装中文字体. 环境信息介绍 [root@thatsit ~]# cat /etc/redhat-release CentOS Linux release ...

  3. Android相关资源

    各类黑客大会资料 https://infocon.org/cons/ 各类课程.视频 https://github.com/Developer-Y/cs-video-courses#security ...

  4. 四、ARM 异常处理

    4.1 模式与异常 当正常程序流程被暂时停止发生异常,例如响应一个来自外设的中断.在处理异常前,必须保护当前的处理器状态,以便在完成处理程序后能恢复到原来的程序 . 异常的类型: Reset unde ...

  5. shell脚本监控Tomcat并重启发送短信

    #!/bin/sh TomcatID=$(ps -ef |grep tomcat |grep -w 'tomcat'|grep -v 'grep'|awk '{print $2}') StartTom ...

  6. DevExpress v19.1新版亮点——WinForms篇(三)

    行业领先的.NET界面控件DevExpress v19.1终于正式发布,本站将以连载的形式介绍各版本新增内容.在本系列文章中将为大家介绍DevExpress WinForms v19.1中新增的一些控 ...

  7. Django数据库查询优化与AJAX

    目录 数据库设计三大范式 orm相关的数据库查询优化 惰性查询 all.only与defer select_related与prefetch_related MTV与MVC模型 MTV(models ...

  8. TinyMCE不可编辑

    1. 通过配置在控件初始化时设置 tinyMCE.init({ readonly : 1 }); 2.tinymce.activeEditor.getBody().setAttribute('cont ...

  9. python-获取类名和方法名,动态创建类和方法及属性

    获取类名和方法名1.在函数外部获取函数名称,用.__name__获取2.在函数内部获取当前函数名称,用sys._getframe().f_code.co_name方法获取3.使用inspect模块动态 ...

  10. 链接收藏:bullet物理引擎不完全指南

    这个也是博客园的文章,编辑得也很好,就不copy了,结尾还有PDF: https://www.cnblogs.com/skyofbitbit/p/4128347.html 完结