用栈实现队列-力扣

比较基础的一道题目,考察使用栈来实现队列,使用两个栈来模拟队列,栈的规则是后进先出,而队列是先进先出。
每次需要对栈进行操作时,将栈a的元素一次挪到栈b中,那么栈b中元素的出栈顺序,正好就是队列元素出队的顺序,在操作完后再将栈b剩余元素挪到栈a中。这里栈a被称为输入栈,栈b被称为输出栈。

class MyQueue {
public:
    MyQueue() {
        stack<int> a;
        stack<int> b;
    }
    
    void push(int x) {
        a.push(x);
    }
    
    int pop() {
        int tmp;
        while(!a.empty()){
            tmp = a.top();
            a.pop();
            b.push(tmp);
        }
        int result = b.top();
        b.pop();
        while(!b.empty()){
            tmp = b.top();
            b.pop();
            a.push(tmp);
        }
        return result;
    }
    
    int peek() {
        int tmp;
        while(!a.empty()){
            tmp = a.top();
            a.pop();
            b.push(tmp);
        }
        int result = b.top();
        while(!b.empty()){
            tmp = b.top();
            b.pop();
            a.push(tmp);
        }
        return result;
    }
    
    bool empty() {
        if(a.empty()){
            return true;
        }else {
            return false;
        }
    }
private:
    stack<int> a;
    stack<int> b;
};

/**
 * 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();
 */

进阶版本,之前的代码,在每次操作时,都需要对栈的元素来回倒,而输出栈在结束操作后为空,修改为只有在输出栈为空时,才将输入栈的元素导入输出栈,这样依然能够保持模拟队列的输出顺序。代码如下:

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    /** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值