Day10 | 232.用栈实现队列、225.用队列实现栈

232.用栈实现队列

栈的特点是先进后出,而队列的特点是先进先出,所以用两个栈,一个先接收元素再将其中元素出栈,压入另一个栈中,即可实现队列

class MyQueue {
public:
    stack<int> s_in;
    stack<int> s_out;
    MyQueue() {

    }
    
    void push(int x) {
        s_in.push(x);
    }
    
    int pop() {
        int res;
        if(s_out.empty()){
            while (!s_in.empty()){
                s_out.push(s_in.top());
                s_in.pop();
            }
        }
        res=s_out.top();
        s_out.pop();
        return res;
    }
    
    int peek() {
        int res= this->pop();
        s_out.push(res);
        return res;
    }
    
    bool empty() {
        if(s_out.empty()&&s_in.empty())
            return 1;
        else
            return 0;
    }
};

225.用队列实现栈

若和上题一样用两个队列元素进出来实现栈,则会发现由于队列先进先出的特性即使将元素从第一个队列出队再入队到第二个队列,出队顺序仍然是先进先出,未发生改变
所以本题思路为,将第二个队列用作“备份”使用,即pop时,q1中仅剩一个元素,其余元素均备份到q2中,pop执行结束后,再将其入队到q1

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

    }
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        int res;
        while (q1.size()>1){
            q2.push(q1.front());
            q1.pop();
        }
        res=q1.front();
        q1.pop();
        while (!q2.empty()){
            q1.push(q2.front());
            q2.pop();
        }
        return res;
    }
    
    int top() {
        int res= this->pop();
        q1.push(res);
        return res;
    }
    
    bool empty() {
        if(q1.empty()&&q2.empty())
            return 1;
        else
            return 0;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值