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

用栈实现队列

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

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

示例:

  1. MyQueue queue = new MyQueue();
  2. queue.push(1);
  3. queue.push(2);
  4. queue.peek(); // 返回 1
  5. queue.pop(); // 返回 1
  6. queue.empty(); // 返回 false

说明:

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

思路

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

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

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

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

代码如下:

java描述

  1. import java.util.Stack;
  2. class MyQueue {
  3. /** Initialize your data structure here. */
  4. Stack<Integer> s1 = new Stack<Integer>();
  5. Stack<Integer> s2 = new Stack<Integer>();
  6. /** Push element x to the back of queue. */
  7. public void push(int x) {
  8. s1.push(x);
  9. }
  10. /** Removes the element from in front of queue and returns that element. */
  11. public int pop() {
  12. if (!s2.isEmpty()) return s2.pop();
  13. while (!s1.isEmpty()) {
  14. int val = s1.pop();
  15. s2.push(val);
  16. }
  17. return s2.pop();
  18. }
  19. /** Get the front element. */
  20. public int peek() {
  21. if (!s2.isEmpty()) return s2.peek();
  22. while (!s1.isEmpty()) {
  23. int val = s1.pop();
  24. s2.push(val);
  25. }
  26. return s2.peek();
  27. }
  28. /** Returns whether the queue is empty. */
  29. public boolean empty() {
  30. return s1.empty() && s2.empty();
  31. }
  32. }
  33. /**
  34. * Your MyQueue object will be instantiated and called as such:
  35. * MyQueue obj = new MyQueue();
  36. * obj.push(x);
  37. * int param_2 = obj.pop();
  38. * int param_3 = obj.peek();
  39. * boolean param_4 = obj.empty();
  40. */

python3描述

  1. from collections import deque
  2. class Stack:
  3. def __init__(self):
  4. self.items = deque()
  5. def push(self, val):
  6. return self.items.append(val)
  7. def pop(self):
  8. return self.items.pop()
  9. def top(self):
  10. return self.items[-1]
  11. def empty(self):
  12. return len(self.items) == 0
  13. class MyQueue:
  14. def __init__(self):
  15. """
  16. Initialize your data structure here.
  17. """
  18. self.s1 = Stack()
  19. self.s2 = Stack()
  20. def push(self, x: int) -> None:
  21. """
  22. Push element x to the back of queue.
  23. """
  24. self.s1.push(x)
  25. def pop(self) -> int:
  26. """
  27. Removes the element from in front of queue and returns that element.
  28. """
  29. if not self.s2.empty():
  30. return self.s2.pop()
  31. while not self.s1.empty():
  32. val = self.s1.pop()
  33. self.s2.push(val)
  34. return self.s2.pop()
  35. def peek(self) -> int:
  36. """
  37. Get the front element.
  38. """
  39. if not self.s2.empty():
  40. return self.s2.top()
  41. while not self.s1.empty():
  42. val = self.s1.pop()
  43. self.s2.push(val)
  44. return self.s2.top()
  45. def empty(self) -> bool:
  46. """
  47. Returns whether the queue is empty.
  48. """
  49. return self.s1.empty() and self.s2.empty()
  50. # Your MyQueue object will be instantiated and called as such:
  51. # obj = MyQueue()
  52. # obj.push(x)
  53. # param_2 = obj.pop()
  54. # param_3 = obj.peek()
  55. # 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. (转载)深入理解Java:内省(Introspector)

    本文转载自:https://www.cnblogs.com/peida/archive/2013/06/03/3090842.html 一些概念: 内省(Introspector) 是Java 语言对 ...

  2. 阿里云服务器ECS装好宝塔 但访问不了面板的解决方法

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

  3. VMware NAT模式设置静态IP(可上网)

    在搞电商架构的高并发高可用时,需要在VMware新建几个linux虚拟机,如果使用VMware的默认网络是自动获取的,但有时候启动虚拟机IP地址会改变,使用很不方便,所以就整理一份静态IP地址设置的方 ...

  4. 【2】PRD文档介绍

    首先,我想说,题主是一个不严肃的人(严肃脸),所以每次干个啥事之前我都喜欢唠唠嗑,说说废话,沟通沟通感情,曾经以为自己将会成为一个幻想中的产品经理那般大展身手,作为非计算机专业出身的应届生,后来才发现 ...

  5. 原来项目更换svn地址

    近期公司由于旧地址装修,临时更换办公地址:同时相应的网络地址也更换了.我们开发项目的svn地址根目录也得改变.所以怎么解决呢? 1.找到项目根文件夹: 右键:

  6. Python 中的type和object详解

    1.python中的类 Python2.x 中的类分为两种,一种是所有继承自object的新式类,另外一种是经典类classobj, 新式类的写法: class A(object): pass 经典类 ...

  7. Postman系列之发送请求(一)

    实验简介 Postman是一款功能强大的网页调试与发送网页HTTP请求的Chrome插件.它能提供功能强大的 Web API 和 HTTP 请求的调试,它能够发送任何类型的HTTP 请求 (GET, ...

  8. Python re 正则表达式【一】【转】

    数量词的贪婪模式与非贪婪模式 正则表达式通常用于在文本中查找匹配的字符串.Python里数量词默认是贪婪的(在少数语言里也可能是默认非贪婪),总是尝试匹配尽可能多的字符:非贪婪的则相反,总是尝试匹配尽 ...

  9. Returning array from function in C

    以下为了通俗易懂,使用意译. I've here very intersting discussion about the best and common ways to return an arra ...

  10. pycharm设置背景颜色

    https://jingyan.baidu.com/article/9faa7231f88570473c28cb88.html