Leetcode的AC指南 —— 栈与队列:232.用栈实现队列

摘要:
**Leetcode的AC指南 —— 栈与队列:232.用栈实现队列 **。题目介绍:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

文章目录

  • 一、题目
  • 二、解析 (go语言版)
    • 1、int型数组作为两个栈
  • 三、其他语言版本
    • Java
    • C++
    • Python

一、题目


题目介绍:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:

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

力扣题目链接

示例 1:

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

提示:
1 <= x <= 9
最多调用 100 次 push、pop、peek 和 empty
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

二、解析 (go语言版)


1、int型数组作为两个栈

  • 思路:

    • 队列中存在两个栈:进栈和出栈
      • 在进栈压入元素,从出栈弹出元素
      • 注意队列先进先出的特点
        • 在出栈弹出元素时,在队列不为空,出栈为空的条件下,依次弹出进栈的元素压入出栈。
          • 这能使先进入队列的元素放在出栈的栈顶 。
        • 然后在需要弹出队列的元素时,弹出出栈的栈顶元素,满足队列先进先出的特点。
          在这里插入图片描述
  • 时间复杂度: push和empty为O(1), pop和peek为O(n)

  • 空间复杂度: O(n)


package maintype MyQueue struct {stackIn  []int // 进栈stackOut []int // 出栈
}// 初始化队列
func Constructor() MyQueue {return MyQueue{stackIn:  make([]int, 0),stackOut: make([]int, 0),}
}// 将队列x推到队列的末尾
func (this *MyQueue) Push(x int) {this.stackIn = append(this.stackIn, x) // 将元素添加到进栈
}// 从队列的开头移除,并返回元素
func (this *MyQueue) Pop() int {inLen, outLen := len(this.stackIn), len(this.stackOut)// 出栈为空时,将进栈中的元素转移到出栈if outLen == 0 {if inLen == 0 { // 队列为空return -1}// 根据先进显出的规则,取出所有 进栈的元素,压入出栈for i := inLen - 1; i >= 0; i-- {this.stackOut = append(this.stackOut, this.stackIn[i])}this.stackIn = []int{}      // 将进栈清空outLen = len(this.stackOut) // 统计出栈中当钱的元素}val := this.stackOut[outLen-1]           // 取出 出栈中最上面的那个元素this.stackOut = this.stackOut[:outLen-1] // 更新出栈return val
}// 返回队列开头的元素
func (this *MyQueue) Peek() int {val := this.Pop() // 弹出队列开头的元素if val == -1 {return -1} // 队列为空this.stackOut = append(this.stackOut, val) // 将弹出的元素压回return val}// 判断队列是否为空,空返回true,不空返回false
func (this *MyQueue) Empty() bool {return len(this.stackIn) == 0 && len(this.stackOut) == 0
}

三、其他语言版本


Java

class MyQueue {Stack<Integer> stackIn;Stack<Integer> stackOut;/** Initialize your data structure here. */public MyQueue() {stackIn = new Stack<>(); // 负责进栈stackOut = new Stack<>(); // 负责出栈}/** Push element x to the back of queue. */public void push(int x) {stackIn.push(x);}/** Removes the element from in front of queue and returns that element. */public int pop() {    dumpstackIn();return stackOut.pop();}/** Get the front element. */public int peek() {dumpstackIn();return stackOut.peek();}/** Returns whether the queue is empty. */public boolean empty() {return stackIn.isEmpty() && stackOut.isEmpty();}// 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中private void dumpstackIn(){if (!stackOut.isEmpty()) return; while (!stackIn.isEmpty()){stackOut.push(stackIn.pop());}}
}

C++

class MyQueue {
public:stack<int> stIn;stack<int> stOut;/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {stIn.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)if (stOut.empty()) {// 从stIn导入数据直到stIn为空while(!stIn.empty()) {stOut.push(stIn.top());stIn.pop();}}int result = stOut.top();stOut.pop();return result;}/** Get the front element. */int peek() {int res = this->pop(); // 直接使用已有的pop函数stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去return res;}/** Returns whether the queue is empty. */bool empty() {return stIn.empty() && stOut.empty();}
};

Python

class MyQueue:def __init__(self):"""in主要负责push,out主要负责pop"""self.stack_in = []self.stack_out = []def push(self, x: int) -> None:"""有新元素进来,就往in里面push"""self.stack_in.append(x)def pop(self) -> int:"""Removes the element from in front of queue and returns that element."""if self.empty():return Noneif self.stack_out:return self.stack_out.pop()else:for i in range(len(self.stack_in)):self.stack_out.append(self.stack_in.pop())return self.stack_out.pop()def peek(self) -> int:"""Get the front element."""ans = self.pop()self.stack_out.append(ans)return ansdef empty(self) -> bool:"""只要in或者out有元素,说明队列不为空"""return not (self.stack_in or self.stack_out)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/419377.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

String在VS与Linux下的区别

目录 一、string的成员 1.VS 2.Linux 二、string的扩容机制 1. VS 2.Linux 一、string的成员 string是C标准库中的一个类模板&#xff0c;用于表示和操作字符串 string在 Windows 与 Linux 中的成员不是相同的 1.VS 4个成员&#xff1a;_str , _size , _capacity 和…

力扣白嫖日记(sql)

前言 练习sql语句&#xff0c;所有题目来自于力扣&#xff08;https://leetcode.cn/problemset/database/&#xff09;的免费数据库练习题。 今日题目&#xff1a; 1050.合作至少三次的演员和导演 表&#xff1a;ActorDirector 列名类型actor_idintdirector_idinttimestamp…

Dart安装(Winodws)

Dart官网&#xff1a; https://dart.dev/ 一、命令行安装 https://dart.dev/get-dart You can install the Dart SDK using Chocolatey. error Important: These commands require administrator rights. Here’s one way to open a Command Prompt window that has admin …

Java大型企业进销存系统

技术框架&#xff1a; SpringBoot Spring Data Jpa SpringMvc Shiro安全认证 完整权限系统 easyui 运行环境&#xff1a; jdk8 IntelliJ IDEA maven 系统介绍&#xff1a; 导航菜单&#xff1a;系统菜单、销售管理、库存管理、统计报表、基础资料、系统管理 系统菜…

Java多线程并发篇----第二十六篇

系列文章目录 文章目录 系列文章目录前言一、什么是 Executors 框架?二、什么是阻塞队列?阻塞队列的实现原理是什么?如何使用阻塞队列来实现生产者-消费者模型?三、什么是 Callable 和 Future?前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分…

记一次多平台免杀PHP木马的制作过程

注意&#xff1a;本文转载自本作者稀土掘金博客 博客地址&#xff1a; 御坂19008号 的个人主页 - 动态 - 掘金 文章目录 前言声明绕过情况使用方法运行环境绕过点介绍技术原理讲解变量传值覆盖模块代码执行阻断模块InazumaPuzzle程序锁定器PerlinNoise危险函数生成与执行类构造…

红队打靶练习:W34KN3SS: 1

目录 信息收集 1、arp 2、nmap 3、nikto 4、gobuster 5、dirsearch WEB web信息收集 目录探测 漏洞利用 openssl密钥碰撞 SSH登录 提权 get user.txt get passwd 信息收集 1、arp ┌──(root㉿ru)-[~/kali] └─# arp-scan -l Interface: eth0, type: EN10MB…

Debian11下编译ADAravis和Motor模块的一条龙过程

Debian11编译EPICS ADAravis记录 一年前整理的上面文&#xff0c;这几天重新走了一遍&#xff0c;有些地方会碰到问题&#xff0c;需要补充些环节&#xff0c;motor模块以前和areaDetector一条龙编译时&#xff0c;总是有问题&#xff0c;当时就没尝试了&#xff0c;这几天尝试…

202312电子学会青少年软件编程等级考试Scratch四级真题

2023年12月电子学会青少年软件编程等级考试Scratch四级真题 单项题 第 1 题 运行下列程序&#xff0c;输入“abcdef”&#xff0c;程序结束后&#xff0c;变量“字符串”是&#xff1f;&#xff08; &#xff09; A&#xff1a;fedcb B&#xff1a;bcdef C&#xff1a;abcde …

【UEFI基础】EDK网络框架(TCP4)

TCP4 TCP4协议说明 相比UDP4&#xff0c;TCP4是一种面向连接的通信协议&#xff0c;因此有更好的可靠性。 TCP4的首部格式如下&#xff1a; 各个参数说明如下&#xff1a; 字段长度&#xff08;bit&#xff09;含义Source Port16源端口&#xff0c;标识哪个应用程序发送。D…

Matplotlib Mastery: 从基础到高级的数据可视化指南【第30篇—python:数据可视化】

文章目录 Matplotlib: 强大的数据可视化工具1. 基础1.1 安装Matplotlib1.2 创建第一个简单的图表1.3 图表的基本组件&#xff1a;标题、轴标签、图例 2. 常见图表类型2.1 折线图2.2 散点图2.3 条形图2.4 直方图 3. 图表样式与定制3.1 颜色、线型、标记的定制3.2 背景样式与颜色…

文件处理的重定义,dup2函数

目录 1.了解dup2函数的参数意义 2.举例子了解dup2函数 3.在模拟shell中加入> , >> , < 的指令 4.stdout和stderr的区别 1.了解dup2函数的参数意义 C中系统调用接口中的open-CSDN博客 可以在我上面的博客中了解到&#xff0c;文件其实是被进程以数组的形式存储…