Leetcode 225. 用队列实现栈

文章提供了两种不同的C++实现,使用两个队列作为数据结构来模拟栈的功能。在push操作中直接入队,pop和top操作则通过将队列元素转移来实现栈的行为。二刷代码对empty方法进行了优化,检查两个队列是否都为空。
摘要由CSDN通过智能技术生成

题目

在这里插入图片描述

Leetcode 225. 用队列实现栈

代码(7.17 首刷自解)

class MyStack {
public:
    queue<int> q1, q2;
    MyStack() {}
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        while(q1.size() > 1) {
            q2.push(q1.front());
            q1.pop();
        }
        int x = q1.front();
        q1.pop();
        swap(q1, q2);
        return x;
    }
    
    int top() {
        return q1.back();
    }
    
    bool empty() {
        return q1.empty();
    }
};

代码(9.22 二刷自解)

class MyStack {
public:
    queue<int> q1, q2;
    MyStack() {

    }
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        while(q1.size() != 1) {
            q2.push(q1.front());
            q1.pop();
        }
        int front = q1.front();
        q1.pop();
        swap(q1, q2);
        return front;
    }
    
    int top() {
        return q1.back();
    }
    
    bool empty() {
        return q1.empty() && q2.empty();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值