day10 - 栈与队列part01

发布时间 2023-08-18 16:43:50作者: zqh2023

232. 用栈实现队列

详解

class MyQueue {
public:
    stack<int> st_in;
    stack<int> st_out;
    MyQueue() {

    }
    
    void push(int x) {
        st_in.push(x);
    }
    
    int pop() {
        if(st_out.empty()){
            while(!st_in.empty()){
                st_out.push(st_in.top());
                st_in.pop();
            }
        }
        int result = st_out.top();
        st_out.pop();
        return result;
    }
    
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        st_out.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }
    
    bool empty() {
        return st_in.size() == 0 && st_out.size() == 0;
    }
};

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

 225. 用队列实现栈

 一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。

class MyStack {
public:
    //一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
    queue<int> queue_1;
    MyStack() {

    }
    
    void push(int x) {
        queue_1.push(x);
    }
    
    int pop() {
        int size = queue_1.size();
        size--;//队尾留着变队首
        while(size-- > 0){
            queue_1.push(queue_1.front());
            queue_1.pop();
        }
        int result = queue_1.front();
        queue_1.pop();
        return result;
    }
    
    int top() {
        return queue_1.back();
    }
    
    bool empty() {
        return queue_1.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();
 */