代码随想录算法训练营第十天|232.用栈实现队列225. 用队列实现栈

文章介绍了如何分别利用栈和队列的数据结构,通过编程实现队列和栈的功能。MyQueue类使用两个栈来模拟队列操作,而MyStack类则通过不断将元素推入队列再弹出的方式实现栈功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

232.用栈实现队列

class MyQueue {
public:
    stack<int>in;
    stack<int>out;
    MyQueue() {

    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        if(out.empty()){
            while(!in.empty()){
                out.push(in.top());
                in.pop();
            }
        }
        int a=out.top();
        out.pop();
        return a;
    }
    
    int peek() {
        int ans=this->pop();
        out.push(ans);
        return ans;
    }
    
    bool empty() {
        return in.empty()&&out.empty();
    }
};

225. 用队列实现栈

class MyStack {
public:
    queue<int> a;
    MyStack() {}

    void push(int x) { a.push(x); }

    int pop() {
        int len = a.size() - 1;
        while (len > 0) {
            a.push(a.front());
            a.pop();
            len--;
        }
        int z = a.front();
        a.pop();
        return z;
    }

    int top() { return a.back(); }

    bool empty() { return a.empty(); }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值