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

232.用栈实现队列

链接: 232.用栈实现队列

class MyQueue {
public:
    stack<int> s1;
    stack<int> s2;

    MyQueue() {

    }
    
    void push(int x) {
        s1.push(x);
    }
    
    int pop() {
        int tmp = 0;
        if(s2.empty())
        {
            while(!s1.empty())
            {
                s2.push(s1.top());
                s1.pop();
            }
        }

        tmp = s2.top();
        s2.pop();
        return tmp;
    }
    
    int peek() {
        int tmp = this->pop();
        s2.push(tmp);
        return tmp;
    }
    
    bool empty() {
        return s1.empty() && s2.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

思路与收获

  1. 本题思路比较简单,只要对栈与队列的特性稍有了解就能理解,只不过在代码实现时尤其是在实现队列的pop操作时,如果出栈为空,则要把入栈的数据全部移送过来,只要出栈不为空,则继续pop出栈的元素,这一点在写代码时可能不会想到,导致代码实现复杂。

225.用队列实现栈

链接: 225.用队列实现栈

class MyStack {
public:
    queue<int> q;

    MyStack() {

    }
    
    void push(int x) {
        q.push(x);
    }
    
    int pop() {
        int result = 0;
        for(int i = 0; i < q.size() - 1; ++i)
        {
            q.push(q.front());
            q.pop();
        }

        result = q.front();
        q.pop();
        return result;
    }
    
    int top() {
        return q.back();
    }
    
    bool empty() {
        return q.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

思路与收获

  1. 本题稍微不太容易想到的地方就是如何只用一个队列模拟栈的功能,想明白队列可以循环就可以成功模拟栈的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值