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. git上传项目已经删除文件,但是Jenkins中没有删除

    jenkins 缓存造成的,需要清理工作空间

  2. docker基础知识普及(一)

    背景 这篇内容是之前给部门同事培训时写的文档,旨在传达一些docker相关概念,有个基本印象,当然,以下内容都来自网络,我只是个搬运工.具体操作在下篇文章中 一.什么是docker? 1. Docke ...

  3. vue 引入jQuery

    http://blog.csdn.net/cly153239/article/details/53067433 vue-cli webpack全局引入jquery 首先在package.json里加入 ...

  4. JMeter4.0分布式调度压测部署

    我们在Loadrunner学过使用Load Generator做肉鸡, 通过Controller来进行脚本和权重的分配来进行分布式压测, Jmeter作为当今的网红性能测试工具,这个功能必须是少不了的 ...

  5. Appium移动自动化测试(一)之环境配置

    移动自动化测试很多公司首选appuim, 要了解它的特点和优势请移步http://www.testclass.net/appium/appium-base-summary/ 要开始自动化测试, 好多人 ...

  6. 六十六:CSRF攻击与防御之CSRF防御之ajax防御和ajax封装

    app里面还是要绑定CSRFProtect from flask_wtf import CSRFProtect # flask_wtf 已经提供CSRF的防御手段CSRFProtect(app) # ...

  7. SQL学习(四)Where语句中的各种匹配方式

    在where语句中,我们需要制定各种条件,条件的各种组合需要用到不同的关键字 一.单条件 如:select * from ticket where name='测试' 二.多条件 1.和(and) 如 ...

  8. C# 实现opc ua服务器的远程连接(转)

    原文转自:https://www.cnblogs.com/dathlin/p/7724834.html OPC UA简介 OPC是应用于工业通信的,在windows环境的下一种通讯技术,原有的通信技术 ...

  9. 【.NET】关于.NET前后台提示框的那点事

    前言 关于提示框,或多或少都用到过,提示框常见方式两种:js原生alert() 和 div模拟弹层:下面以一个常见的需求业务场景来展现提示框的那点事: 正文内容 客户:需求方: 小白:实现方(全权负责 ...

  10. 安卓新发布机制----app bundle

    Android App Bundle是一种改进的应用程序打包方式,能大幅度减少应用体积 unity可以直接导出appbundle,只需要在导出的时候勾选 但是通常项目有sdk离不开java端,我这里是 ...