代码随想录算法训练营第十天 | 了解栈

此帖仅作打卡用,过于简单,建议跳过

232.用栈实现队列

根据题意,用俩栈来回倒就行

code

class MyQueue {
public:
    stack<int> q1;
    stack<int> q2;
    MyQueue() {}
    void push(int x) {
        while(!q2.empty()){
            int pipe = q2.top();
            q2.pop();
            q1.push(pipe);
        }
        q1.push(x);
    }
    int pop() {
        while(!q1.empty()){
            int pipe = q1.top();
            q1.pop();
            q2.push(pipe);
        }
        int ans = q2.top();
        q2.pop();
        return ans;
    }
    int peek() {
        while(!q1.empty()) {
            int pipe = q1.top();
            q1.pop();
            q2.push(pipe);
        }
        return q2.top();
    }
    bool empty() {
        return q1.empty() && q2.empty();
    }
};

225.用队列实现栈

一个双端队列完事

code

class MyStack {
public:
    deque<int> d1;
    MyStack() {}
    void push(int x) {
        d1.push_front(x);
    }
    int pop() {
        int p = d1.front();
        d1.pop_front();
        return p;
    }
    int top() {
        return d1.front();
    }
    bool empty() {
        return d1.empty();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值