代码随想录二刷 Day 10

232. Implement Queue using Stacks

题目还是不难,就是stack和queue的各种函数和操作需要记一下。思路就是用两个stack,一个座位出,另一个作为入;

class MyQueue {
public:
    stack<int> In;
    stack<int> Out;
    MyQueue() {
        //stack<int> In;
        //stack<int> Out;这两行不能放在这里面
    }
    
    void push(int x) {
        In.push(x);
    }
    
    int pop() {
        if(Out.empty() == 1) { //这个empty函数不会用
            while(In.empty() != 1) {
                Out.push(In.top());
                In.pop();
            }
        }
        int result = Out.top();
        Out.pop();
        return result;
    }
    
    /** Get the front element. */
    int peek() {
        // 方法是把最上面的那个数弹出来,然后再加进去,在这个过程中赋值
        int result = this->pop();
        Out.push(result);
        return result;
    }
    
    bool empty() {
        return In.empty() && Out.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();
 */



232. Implement Queue using Stacks

class MyQueue {
public:
    stack<int> In;
    stack<int> Out;
    MyQueue() {
        //stack<int> In;
        //stack<int> Out;这两行不能放在这里面
    }
    
    void push(int x) {
        In.push(x);
    }
    
    int pop() {
        if(Out.empty() == 1) { //这个empty函数不会用
            while(In.empty() != 1) {
                Out.push(In.top());
                In.pop();
            }
        }
        int result = Out.top();
        Out.pop();
        return result;
    }
    
    /** Get the front element. */
    int peek() {
        // 方法是把最上面的那个数弹出来,然后再加进去,在这个过程中赋值
        int result = this->pop();
        Out.push(result);
        return result;
    }
    
    bool empty() {
        return In.empty() && Out.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();
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值