当前位置: 首页 > news >正文

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

题目描述 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();
    }
};
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;
    }
}

相关文章:

  • Java-13
  • Kafka系列之:记录一次源头数据库刷数据,造成数据丢失的原因
  • Chrome 推出全新的 DOM API,彻底革新 DOM 操作!
  • 【MySQL】索引和视图
  • Starlink卫星动力学系统仿真建模第七讲-卫星姿轨控系统(Attitude and Orbit Control System, AOCS)设计规范
  • 智信BI:解决Power BI全面兼容问题的新选择
  • List模拟实现
  • CellChat前沿:spaCI:通过自适应图模型破译空间蜂窝通信
  • vs构建网络安全系统 网络安全和网络搭建
  • 在群晖上使用Docker安装思源笔记
  • 【Node.js】包的结构及发布
  • 深度学习学习笔记(34周)
  • 如何评估光伏项目是否可行?需要投资多少?
  • 分类解析决策模型
  • 【从0做项目】Java音缘心动(5)———上传、播放音乐
  • springboot初始化代码
  • Power Query M函数
  • <02.22>Leetcode100
  • JVM内存模型
  • 七星棋牌顶级运营产品全开源修复版源码教程:6端支持,200+子游戏玩法,完整搭建指南(含代码解析)
  • 在国外做网站推广/市场营销
  • 怎么区分模板网站和定制网站/高级seo优化招聘
  • 华为荣耀商城官网/洛阳seo网站
  • 金融做推广的网站/吸引人的微信软文范例
  • discuz导入wordpress/seo怎么优化武汉厂商
  • 当当网电子商务网站建设特点/湖南seo优化价格