来源: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. 04java基础——多态

    1.多态 1.1多态的概念 现实事物经常会体现出多种形态,如学生,学生是人的一种,则一个具体的同学张三既是学生也是人,即出现两种形态. 所谓多态就是指程序中定义的引用变量所指向的具体类型和通过该引用变 ...

  2. pandas的数据统计函数

    # 1汇总类统计 # 2唯一去重和按值计数 # 3 相关系数和协方差 import pandas as pd # 0 读取csv数据 df = pd.read_csv("beijing_ti ...

  3. java tomcat虚拟目录的深入了解

    我们知道,Web网站中的内容(包括网页,图片,音频文件等)一般都存放在App的目录下.但随着网站内容的不断丰富,用户需要把不同层次的内容组织成网站的子目录.我们通常的做法是在网站主目录下新建子目录,并 ...

  4. css多种方式实现双飞翼布局

    圣杯布局.双飞翼布局效果图 从效果图来看圣杯布局.双飞翼布局效果是一样一样的.圣杯布局.双飞翼布局就是左右两侧宽度固定,中间内容宽度自适应,即100% 圣杯布局 <style> *{ ma ...

  5. 锁,threading local,以及生产者和消费者模型

    1.锁:Lock(一次放行一个) 线程安全,多线程操作时,内部会让所有的线程排队处理. 线程不安全:+人=>排队处理 以后锁代码块 v=[] lock=threading.Lock()#声明锁 ...

  6. [CF286C] Main Sequence

    问题描述 定义幸运数列: 空数列是幸运数列 如果 S 是幸运数列,那么 {r, S, -r} 也是幸运数列 (r > 0) 如果 S 和 T 都是幸运数列,那么 {S, T} 也是幸运数列 给定 ...

  7. 【JavaScript】包装类

    包装类 String().Number().Boolean() String() 可以将基本数据类型的字符串转换为String对象 var string = new String("hell ...

  8. linux运维、架构之路-Hadoop完全分布式集群搭建

    一.介绍 Hadoop实现了一个分布式文件系统(Hadoop Distributed File System),简称HDFS.HDFS有高容错性的特点,并且设计用来部署在低廉的(low-cost)硬件 ...

  9. CSS3文本阴影、边框阴影

    CSS3添加阴影 一.使用text-shadow属性为文本添加阴影 二.使用box-shadow属性为边框添加阴影 一.为文本添加阴影 text-shadow     使用text-shadow,可以 ...

  10. CF 480 B Long Jumps (map标记)

    题目链接:http://codeforces.com/contest/480/problem/B 题目描述:     Long Jumps   Valery is a PE teacher at a ...