leecode刷题(26)-- 用栈实现队列

用栈实现队列

使用栈实现队列的下列操作:

  • push(x) -- 将一个元素放入队列的尾部。
  • pop() -- 从队列首部移除元素。
  • peek() -- 返回队列首部的元素。
  • empty() -- 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();

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

说明:

  • 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

思路

首先了解下栈和队列的特点:

  • 栈:后进先出
  • 队列:先进后出

所以我们只用一个栈的话是无法实现队列的操作的。不妨换个思路,我们用两个栈来实现队列:

当栈2不为空时直接 pop,否则把栈1的所有元素放到栈2然后执行栈2 pop 操作。

代码如下:

java描述

import java.util.Stack;

class MyQueue {

    /** Initialize your data structure here. */
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>(); /** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
} /** Removes the element from in front of queue and returns that element. */
public int pop() {
if (!s2.isEmpty()) return s2.pop();
while (!s1.isEmpty()) {
int val = s1.pop();
s2.push(val);
}
return s2.pop();
} /** Get the front element. */
public int peek() {
if (!s2.isEmpty()) return s2.peek();
while (!s1.isEmpty()) {
int val = s1.pop();
s2.push(val);
}
return s2.peek();
} /** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty() && s2.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();
*/

python3描述

from collections import deque

class Stack:
def __init__(self):
self.items = deque() def push(self, val):
return self.items.append(val) def pop(self):
return self.items.pop() def top(self):
return self.items[-1] def empty(self):
return len(self.items) == 0 class MyQueue: def __init__(self):
"""
Initialize your data structure here.
"""
self.s1 = Stack()
self.s2 = Stack() def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.s1.push(x) def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if not self.s2.empty():
return self.s2.pop()
while not self.s1.empty():
val = self.s1.pop()
self.s2.push(val)
return self.s2.pop() def peek(self) -> int:
"""
Get the front element.
"""
if not self.s2.empty():
return self.s2.top()
while not self.s1.empty():
val = self.s1.pop()
self.s2.push(val)
return self.s2.top() def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return self.s1.empty() and self.s2.empty() # 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()

总结

可以看出,java支持栈,我们可以直接调用java.util.Stack ,而 python 不支持栈,我们可以自己使用 deque(双端队列),来模拟一个栈。时间和内存对比如下:

leecode刷题(26)-- 用栈实现队列的更多相关文章

  1. C#LeetCode刷题之#232-用栈实现队列​​​​​​​​​​​​​​(Implement Queue using Stacks)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4108 访问. 使用栈实现队列的下列操作: push(x) -- ...

  2. leecode刷题(27)-- 合并k个排序链表

    leecode刷题(27)-- 合并k个排序链表 合并k个排序链表 合并 k 个排序链表,返回合并后的排序链表.请分析和描述算法的复杂度. 示例: 输入: [ 1->4->5, 1-> ...

  3. leecode刷题(22)-- 反转数组

    leecode刷题(22)-- 反转数组 反转数组 反转一个单链表. 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3-> ...

  4. leecode刷题(21)-- 删除链表的倒数第N个节点

    leecode刷题(21)-- 删除链表的倒数第N个节点 删除链表的倒数第N个节点 描述: 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点. 示例: 给定一个链表: 1->2- ...

  5. leecode刷题(20)-- 删除链表中的节点

    leecode刷题(20)-- 删除链表中的节点 删除链表中的节点 描述: 请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点. 现有一个链表 -- head = ...

  6. leecode刷题(19)-- 最长公共前缀

    leecode刷题(19)-- 最长公共前缀 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: [&quo ...

  7. leecode刷题(18)-- 报数

    leecode刷题(18)-- 报数 报数 描述: 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数.其前五项如下: 1. 1 2. 11 3. 21 4. 1211 5. 1112 ...

  8. leecode刷题(16)-- 字符串转换整数

    leecode刷题(16)-- 字符串转换整数 字符串转换整数 描述: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格 ...

  9. leecode刷题(17)-- 实现StrStr

    leecode刷题(17)-- 实现StrStr 实现StrStr 描述: 实现 strStr() 函数. 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串 ...

随机推荐

  1. C++入门经典-例8.9-抽象类,纯虚函数,创建纯虚函数

    1:包含有纯虚函数的类称为抽象类,一个抽象类至少具有一个纯虚函数.抽象类只能作为基类派生出的新的子类,而不能在程序中被实例化(即不能说明抽象类的对象),但是可以使用指向抽象类的指针.在程序开发过程中并 ...

  2. JS基础_变量提升和函数提升

    1.在函数中,不使用var声明的变量都会变为全局变量 function fun(){ d=10; //window.d=10; }; console.log(10);//10 2.定义形参就相当于在函 ...

  3. beta week 2/2 Scrum立会报告+燃尽图 04

    此作业要求参见https://edu.cnblogs.com/campus/nenu/2019fall/homework/9957 一.小组情况 组长:贺敬文组员:彭思雨 王志文 位军营 徐丽君队名: ...

  4. SQL optimizer -Query Optimizer Deep Dive

    refer: http://sqlblog.com/blogs/paul_white/archive/2012/04/28/query-optimizer-deep-dive-part-1.aspx  ...

  5. CMD命令行管道命令

    一.什么是管道命令 管道命令能够将一个命令的执行结果经过筛选,只保留我们需要的信息. 如 dir 命令会显示目录下所有文件夹和文件,可以使用管道命令| findstr "" 将di ...

  6. 【React自制全家桶】九、Redux入手

    一.React项目中为什么要用Redux 上图: 左图当使用纯React开发稍微大点的项目,因为React数据是瀑布式的,只能通过父子组件传递数据,所以实现关系不大的两React的组件之间的数据传递就 ...

  7. Unix介绍

    1965年,AT&T贝尔电话实验室.通用电气公司.麻省理工学院MAC课题组一起联合开发一个称为Multics的新操作系统.该项目目的是让大型主机可以同时提供300台以上的终端机连接使用.其被设 ...

  8. Windows下Elasticsearch安装问题处理

    按ES官网的安装方法正常安装就行了.可能遇到的其他问题. 1.报jvm.dll不存在. 只需要重新安装JDK过后,会有jdk1.8.0_73目录和jre1.8.0_73目录.因为java就喜欢玩这种“ ...

  9. Redis集群配置和常见异常解决

    前文 Redis的Cluster集群,是在分布式且开源环境下最佳的高可用解决方案,可以有效的解决服务器宕机下或高并发下,数据的完整性. 文档前提 Redis 3.0版本或更高版本.(3.0版本开始支持 ...

  10. Python之数组

    前言 由于Python的数据结构较为灵活,长期使用java编程的我,有时候可能就搞混淆了.此时,记录一些骚操作. 不定长二维数组 array = [4,65,46,57,5]; array2d = [ ...