算法13(力扣225)-用队列实现栈

news/2025/2/8 18:28:01 标签: 算法, leetcode

1、问题

        请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

            实现 MyStack 类:

            void push(int x) 将元素 x 压入栈顶。

            int pop() 移除并返回栈顶元素。

            int top() 返回栈顶元素。

            boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

2、示例

        输入:["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []]

        输出:[null, null, null, 2, 2, false]

        解释:

            MyStack myStack = new MyStack();

            myStack.push(1);

            myStack.push(2);

            myStack.top(); // 返回 2

            myStack.pop(); // 返回 2

            myStack.empty(); // 返回 False

3、实现思路

(1)理解题意

(2)实现思路,按照正常的数组来即可,但是需要记住队和栈的特点

4、具体步骤

(1)创建栈:定义两个队列,其中一个用来处理插入、判空,另一个用来处理返回栈顶元素操作、弹出栈顶元素的操作

(2)push操作:插入,给queue1使用push插入即可

(3)pop弹出操作:栈是先进后出,队是先进先出,将队1的第一个弹出作为队2的输入,然后队2就是队1的逆序(队1剩的最后一个元素就是栈顶元素,即需要删除的元素),然后将剩余元素按照相同的方法返回队1

(4)top返回栈顶元素:和pop相似,只是不删除栈顶元素,使用临时变量存储,然后将队1剩余的元素压入队2,然后将队2所有的元素返回给队1

(5)empty判断栈是否为空(判断队1的长度即可)

5、完整代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>用队列实现栈</title>
  </head>
  <body>
    <p>
        请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

        <p>
            <h4>
                实现 MyStack 类:
            </h4>
            void push(int x) 将元素 x 压入栈顶。<br>
            int pop() 移除并返回栈顶元素。<br>
            int top() 返回栈顶元素。<br>
            boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
        </p>
 
    </p>
    <p>
        输入:["MyStack", "push", "push", "top", "pop", "empty"]
        [[], [1], [2], [], [], []]<br>
        输出:[null, null, null, 2, 2, false]
        <p>
            解释:<br>
            MyStack myStack = new MyStack();<br>
            myStack.push(1);<br>
            myStack.push(2);<br>
            myStack.top(); // 返回 2<br>
            myStack.pop(); // 返回 2<br>
            myStack.empty(); // 返回 False<br>
        </p>
    </p>
    <script> 
    // 创建栈
        var MyStack = function() {
            this.queue1=[]
            this.queue2=[]   
        };

        /** 
         * @param {number} x
         * @return {void}
         */
        // 给栈中添加元素
        MyStack.prototype.push = function(x) {
            this.queue1.push(x)
        };

        /**
         * @return {number}
         */
        // 弹出(栈顶元素)(队1的最后一个元素)
        MyStack.prototype.pop = function() {
            // 栈是先进后出,队是先进先出,将队1的第一个弹出作为队2的输入,然后队2就是队1的逆序(队1剩的最后一个元素就是栈顶元素,即需要删除的元素),然后将剩余元素按照相同的方法返回队1
            let topElement;
            while (this.queue1.length > 1) {
                this.queue2.push(this.queue1.shift())
            }
            topElement = this.queue1.shift()
            while (this.queue2.length) {
                this.queue1.push(this.queue2.shift());
            }
            return topElement;
        };

        /**
         * @return {number}
         */
        // 返回栈顶元素
        MyStack.prototype.top = function() {
            // 和pop相似,只是不删除栈顶元素,使用临时变量存储,然后将队1剩余的元素压入队2,然后将队2所有的元素返回给队1
            let topElement;
             while (this.queue1.length > 1) {
                this.queue2.push(this.queue1.shift())
            }
            topElement = this.queue1[0]
            this.queue2.push(this.queue1.shift())
            while (this.queue2.length > 0) {
                this.queue1.push(this.queue2.shift());
            }
            return topElement;
        };

        /**
         * @return {boolean}
         */
        // 判断栈是否为空(判断队1的长度即可)
        MyStack.prototype.empty = function() {
            return !this.queue1.length;
        };

        var myStack = new MyStack();
        myStack.push(1);
        myStack.push(2);
        console.log(myStack.top()); // Output: 2
        console.log(myStack.pop()); // Output: 2
        console.log(myStack.empty()); // Output: false
        /** 
         * Your MyStack object will be instantiated and called as such:
         * var obj = new MyStack()
         * obj.push(x)
         * var param_2 = obj.pop()
         * var param_3 = obj.top()
         * var param_4 = obj.empty()
         */
    </script>
  </body>
</html>

6、力扣通过代码

   // 创建栈
        var MyStack = function() {
            this.queue1=[]
            this.queue2=[]   
        };

        /** 
         * @param {number} x
         * @return {void}
         */
        // 给栈中添加元素
        MyStack.prototype.push = function(x) {
            this.queue1.push(x)
        };

        /**
         * @return {number}
         */
        // 弹出
        MyStack.prototype.pop = function() {
            // 栈是先进后出,队是先进先出,将队1的第一个弹出作为队2的输入,然后队2就是队1的逆序(队的第一个元素就是栈顶元素,即需要删除的元素)
            let topElement;
            while (this.queue1.length > 1) {
                this.queue2.push(this.queue1.shift())
            }
            topElement = this.queue1.shift()
            while (this.queue2.length) {
                this.queue1.push(this.queue2.shift());
            }
            return topElement;
        };

        /**
         * @return {number}
         */
        // 返回栈顶元素
        MyStack.prototype.top = function() {
            let topElement;
             while (this.queue1.length > 1) {
                this.queue2.push(this.queue1.shift())
            }
            topElement = this.queue1[0]
            this.queue2.push(this.queue1.shift())
            while (this.queue2.length > 0) {
                this.queue1.push(this.queue2.shift());
            }
            return topElement;
        };

        /**
         * @return {boolean}
         */
        // 判断栈是否为空
        MyStack.prototype.empty = function() {
            return !this.queue1.length;
        };


http://www.niftyadmin.cn/n/5845201.html

相关文章

硬核技术:小程序能够调用手机的哪些传感器

一、加速度传感器 小程序可以调用手机的加速度传感器来检测设备的运动状态。加速度传感器能够测量设备在三个轴&#xff08;X、Y、Z&#xff09;上的加速度变化。通过分析这些数据&#xff0c;小程序可以实现一些功能&#xff0c;如运动检测、步数统计、游戏中的动作感应等。 健…

UE学习日志#24 C++笔记#10 内存管理1

注&#xff1a;此文章为学习笔记&#xff0c;只记录个人不熟悉或备忘的内容 1 使用动态内存 1.1 如何描述动态内存 区分好栈上自动分配的变量和自由存储区的变量。 1.2 分配和释放 1.使用new和delete delete ptr;ptrnullptr; 2.避免在C中使用malloc()和free()&#xff0c;…

CRM系统中的数据分析和报表功能如何帮助企业?

CRM系统中的数据分析和报表功能&#xff1a;企业战略决策的得力助手 在当今竞争激烈的商业环境中&#xff0c;企业要想保持竞争力并实现持续增长&#xff0c;必须依靠精准的数据分析来制定有效的战略决策。而客户关系管理&#xff08;CRM&#xff09;系统的数据分析与报表生成…

【鸿蒙开发】第二十四章 AI - Core Speech Kit(基础语音服务)

目录 1 简介 1.1 场景介绍 1.2 约束与限制 2 文本转语音 2.1 场景介绍 2.2 约束与限制 2.3 开发步骤 2.4 设置播报策略 2.4.1 设置单词播报方式 2.4.2 设置数字播报策略 2.4.3 插入静音停顿 2.4.4 指定汉字发音 2.5 开发实例 3 语音识别 3.1 场景介绍 3.2 约束…

使用Python和`moviepy`库从输入的图片、动图和音频生成幻灯片式视频的示例代码

下面是一个使用Python和moviepy库从输入的图片、动图和音频生成幻灯片式视频的示例代码。在这个示例中&#xff0c;我们将依次展示每张图片或动图&#xff0c;同时播放音频。 from moviepy.editor import ImageClip, VideoFileClip, AudioFileClip, concatenate_videoclipsdef…

【redis】缓存设计规范

本文是 Redis 键值设计的 14 个核心规范与最佳实践&#xff0c;按重要程度分层说明&#xff1a; 一、通用数据类型选择 这里我们先给出常规的选择路径图。 以下是对每个步骤的分析&#xff1a; 是否需要排序&#xff1f;&#xff1a; zset&#xff08;有序集合&#xff09;用…

【B站保姆级视频教程:Jetson配置YOLOv11环境(八)TensorRT模型导出】

Jetson配置YOLOv11环境&#xff08;8&#xff09;TensorRT模型导出 文章目录 1. Conda 虚拟环境配置TensorRT2. onnx, onnxslim, onnxruntime-gpu安装2.1 简介2.2 onnx&#xff0c;onnxslim安装2.3 onnxruntime-gpu安装 3. TensorRT格式导出&推理验证3.1 模型导出为TensorR…

启明星辰发布MAF大模型应用防火墙产品,提升DeepSeek类企业用户安全

2月7日&#xff0c;启明星辰面向DeepSeek等企业级大模型业务服务者提供的安全防护产品——天清MAF&#xff08;Model Application Firewall&#xff09;大模型应用防火墙产品正式发布。 一个新赛道将被开启…… DeepSeek的低成本引爆赛道规模 随着DeepSeek成为当前最热的现象级…