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. Windows环境下Zookeeper的安装和部署(单机模式和伪集群模式)

    第一部分:单机模式 1)下载地址:http://www.pirbot.com/mirrors/apache/zookeeper/,建议下载stable版本 2)解压缩 将下载好的压缩包解压到指定目录, ...

  2. 使用root配置的hadoop启动时报错

    一.报错信息: Starting namenodes on [master]         ERROR: Attempting to operate on hdfs namenode as root ...

  3. python:BeautifulSoup学习

    上一篇说到用BeautifulSoup解析源代码,下面我们就来实战一下: from bs4 import BeautifulSoup html = urllib.request.urlopen('ht ...

  4. LC 961. N-Repeated Element in Size 2N Array【签到题】

    In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeate ...

  5. Hibernate查询总的记录数

    1. 原生sql String hql="select count(*) from product" ;//此处的product是数据库中的表名 Query query=sessi ...

  6. JAVA多线程程序ProgressBar2

    JAVA多线程程序ProgressBar2 题目简介: 思路分析:与上一篇:JAVA多线程程序ProgressBar类似,本篇避免过于冗杂,所以在此没有给出. 实验代码: import java.aw ...

  7. centos6.5 内核 :2.6.32 升级内核

    问题:    CentOS 6.5 的内核一般都是2.6,在2.6的内核下,Docker运行会比较卡,所以一般会选择升级到更高版本,本次教程升级版本为4.4.102 一.升级内核 1.查看内核版本 u ...

  8. Spring集成CXF获取HttpServletRequest,HttpServletResponse

    最近的项目中,在Spring继承CXF中要用到request来获取IP,所以先要获取到HttpServletRequest对象,具体方法如下: 1.配置文件: <jaxrs:server id= ...

  9. Django使用消息提示简单的弹出个对话框

    1.下面就来介绍一下如何简单的显示一个消息提示,好像js可以控制,不过这里用了django.contrib.messages这个库 2.首先呢,在项目的settings.py有默认配置一个django ...

  10. 恒生投资交易系统性O3性能测量

    --每秒交易所成交量select b.tps, b.l_business_time from (select count(*) as tps, a.l_business_time from trade ...