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. 阿里云服务器ECS装好宝塔 但访问不了面板的解决方法

    (SSH) (phpmyadmin) 如果你进入面板里修改了面板端口或FTP端口,记得要在安全组和面板防火墙放行相应端口

  2. Walkthrough: My first WPF desktop application

    Walkthrough: My first WPF desktop application This article shows you how to develop a Windows Presen ...

  3. 使用Statement对象执行静态sql语句

    import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java ...

  4. 百度AI---语音识别

    题记:娱乐性的玩玩百度接口. 说实话,其接口个人觉得有点烂,重试了好几个音频文件才成功. 1.重新申请AppID.SecretKey .API Key. 链接:https://console.bce. ...

  5. python 连接mysql数据库:pymysql

    示例:import pymysql conn=pymysql.connect( host="127.0.0.1", #数据库IP port=3306, #数据库端口 user=&q ...

  6. Linux crontab 每5秒钟执行一次 shell 脚本 的方法

    Linux crontab 每5秒钟执行一次 shell 脚本 的方法 由于 Linux 的 crontab 的定时命令格式如下: minute hour day-of-month month-of- ...

  7. linux常用命令(12)head命令

    head 与 tail 就像它的名字一样的浅显易懂,它是用来显示开头或结尾某个数量的文字区块,head 用来显示档案的开头至标准输出中,而 tail 想当然尔就是看档案的结尾.1 命令格式head [ ...

  8. SSO单点登录统一身份认证系统

    什么是单点登录 简单点说就是公司有A,B两个系统,我登录了A系统之后再跳转到B系统可以直接访问,而不需要再次登录B系统. 几种常见的单点登录实现方式 在讲解单点登录之前先讲解几个基本的概念: Cook ...

  9. Mac上解决Chrome浏览器跨域问题

    最近做前端开发总是遇到一个很奇怪的现象,同一个AJAX请求,在Chrome里调试的时候就会提示跨域,但是在手机模拟器或者真机上调试的时候就不会,于是百度了一下,发现是Chrome的安全策略导致的,需要 ...

  10. XCTF (app2)

    打开app,有两个输入框和一个按钮.点击按钮会跳转到新的页面显示Waiting for you. 打开JEB反编译. 如果两个输入框的长度都不为0,那么获取这两个值到v0和v1中,Log记录日志. 创 ...