C++/JavaScript ⭐算法OJ⭐用两个队列实现栈

news/2025/2/24 15:29:18

题目描述 225. Implement Stack using Queues

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

  • void push(int x) Pushes element x to the top of the stack.
  • int pop() Removes the element on the top of the stack and returns it.
  • int top() Returns the element on the top of the stack.
  • boolean empty() Returns true if the stack is empty, false otherwise.

Notes:

  • You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
  • Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue’s standard operations.

使用两个队列实现一个后进先出(LIFO)的栈。实现的栈需要支持普通栈的所有操作(pushtoppopempty)。

解题思路

  • 使用两个队列 q1q2 来模拟栈的行为。
  • 每次 push 操作时,将新元素加入非空队列中。
  • 每次 poptop 操作时,将非空队列中的元素依次移动到另一个队列,直到剩下最后一个元素,该元素就是栈顶元素。
  • empty 操作只需检查两个队列是否都为空。
#include <queue>

class MyStack {
private:
    queue<int> q1;
    queue<int> q2;

public:
    MyStack() {}

    void push(int x) {
        // 将新元素加入非空队列
        if (!q1.empty()) {
            q1.push(x);
        } else {
            q2.push(x);
        }
    }

    int pop() {
        // 找到非空队列
        queue<int>& nonEmptyQueue = q1.empty() ? q2 : q1;
        queue<int>& emptyQueue = q1.empty() ? q1 : q2;

        // 将非空队列中的元素移动到空队列,直到剩下最后一个元素
        while (nonEmptyQueue.size() > 1) {
            emptyQueue.push(nonEmptyQueue.front());
            nonEmptyQueue.pop();
        }

        // 返回并移除最后一个元素
        int topElement = nonEmptyQueue.front();
        nonEmptyQueue.pop();
        return topElement;
    }

    int top() {
        // 找到非空队列
        queue<int>& nonEmptyQueue = q1.empty() ? q2 : q1;
        queue<int>& emptyQueue = q1.empty() ? q1 : q2;

        // 将非空队列中的元素移动到空队列,直到剩下最后一个元素
        while (nonEmptyQueue.size() > 1) {
            emptyQueue.push(nonEmptyQueue.front());
            nonEmptyQueue.pop();
        }

        // 返回最后一个元素,但不移除
        int topElement = nonEmptyQueue.front();
        emptyQueue.push(topElement); // 将最后一个元素放回队列
        nonEmptyQueue.pop();
        return topElement;
    }

    bool empty() {
        return q1.empty() && q2.empty();
    }
};
javascript">class MyStack {
    constructor() {
        this.q1 = [];
        this.q2 = [];
    }

    push(x) {
        // 将新元素加入非空队列
        if (this.q1.length > 0) {
            this.q1.push(x);
        } else {
            this.q2.push(x);
        }
    }

    pop() {
        // 找到非空队列
        let nonEmptyQueue = this.q1.length > 0 ? this.q1 : this.q2;
        let emptyQueue = this.q1.length > 0 ? this.q2 : this.q1;

        // 将非空队列中的元素移动到空队列,直到剩下最后一个元素
        while (nonEmptyQueue.length > 1) {
            emptyQueue.push(nonEmptyQueue.shift());
        }

        // 返回并移除最后一个元素
        return nonEmptyQueue.shift();
    }

    top() {
        // 找到非空队列
        let nonEmptyQueue = this.q1.length > 0 ? this.q1 : this.q2;
        let emptyQueue = this.q1.length > 0 ? this.q2 : this.q1;

        // 将非空队列中的元素移动到空队列,直到剩下最后一个元素
        while (nonEmptyQueue.length > 1) {
            emptyQueue.push(nonEmptyQueue.shift());
        }

        // 返回最后一个元素,但不移除
        let topElement = nonEmptyQueue[0];
        emptyQueue.push(nonEmptyQueue.shift()); // 将最后一个元素放回队列
        return topElement;
    }

    empty() {
        return this.q1.length === 0 && this.q2.length === 0;
    }
}

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

相关文章

AI助力小微企业技术开发规范化管理 | 杂谈

AI助力小微企业技术开发规范化管理 在小型技术研发企业中&#xff0c;人员配置紧张&#xff0c;往往一名员工需要承担多项职务和任务。例如&#xff0c;后端程序开发人员可能同时要负责需求调研、数据库设计、后端设计及开发&#xff0c;甚至在某些情况下还需兼任架构师的角色。…

Github 2025-02-23 php开源项目日报 Top9

根据Github Trendings的统计,今日(2025-02-23统计)共有9个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量PHP项目9JavaScript项目2Shell项目1TypeScript项目1Blade项目1Java项目1ASP项目1Vue项目1Laravel:表达力和优雅的 Web 应用程序框架 创建周期:…

彻底卸载kubeadm安装的k8s集群

目录 一、删除资源 二、停止k8s服务 三、重置集群 四、卸载k8s安装包 五、清理残留文件和目录 六、删除k8s相关镜像 七、重启服务器 一、删除资源 # 删除集群中的所有资源&#xff0c;包括 Pod、Deployment、Service&#xff0c;任意节点执行 kubectl delete --all pod…

mysql的源码包安装

安装方式一&#xff1a;&#xff08;编译好的直接安装&#xff09; 1.添加一块10G的硬盘&#xff0c;给root逻辑卷扩容 &#xff08;下面安装方式二有&#xff0c;一模一样的装就行&#xff0c;我就不写了&#xff0c;再写的话篇幅就太长了&#xff09; 2.下载编译好的源码包…

数据库增删查改sql语句

一、数据库、表的建立/删除 新建数据库&#xff1a; create database 数据库名; #create database students; #新建一个students的数据库 新建表&#xff1a; 在建表之前&#xff0c;需要指定在哪个数据库下建表&#xff0c;使用use 数据库名; 接下来就可以建表了&#xff…

电子技能大赛选题

关于电子技能大赛的选题&#xff0c;我们需要综合多方面因素去考虑&#xff0c;比如难度&#xff0c;炫酷程度&#xff0c;能接受的成本&#xff0c;进度能不能掌控&#xff0c;有哪些难点需要攻破&#xff0c;能从外部获得什么资源等等。比如小车&#xff0c;会有一些结构件的…

前后端分离系统架构:基于Spring Boot的最佳实践

前后端分离系统架构图描绘了一个基于Springboot的前端后台分离的系统架构。它强调了前端&#xff08;客户端&#xff09;与远程&#xff08;服务器&#xff09;的解耦&#xff0c;通过API接口进行交互&#xff0c;分别独立开发和部署。 前后端分离系统架构图 从上到下&#xff…

如果二者隔离级别不一致,以哪个为主。例如@Transactional 隔离级别是RC,mysql是RR

如果 Spring 的 Transactional 隔离级别 和 数据库的隔离级别 不一致&#xff0c;最终生效的隔离级别取决于以下两种情况&#xff1a; 1. Spring 隔离级别优先级更高 Spring 的行为&#xff1a; 当你在 Transactional 注解中显式配置了隔离级别&#xff08;例如 isolation Iso…