2022年10月21日学习打卡

82 阅读2分钟

day10

232.用栈实现队列

大家可以先看视频,了解一下模拟的过程,然后写代码会轻松很多。

题目链接/文章讲解/视频讲解:programmercarl.com/0232.%E7%94…

个人思路: 栈先进后出,队列先进先出,它们的区别在于输出上。设定两个栈,一个为输入栈,一个为输出栈,当栈需要执行输出操作时,从输出栈中寻找元素输出,而输出栈的元素主要来源于输入栈中,peek函数可以采用上面的函数进行实现,避免代码的冗余性。

代码:

class MyQueue {
public:
    stack<int> stdIn;
    stack<int> stdOut;

    MyQueue() {

    }
    
    void push(int x) {
        stdIn.push(x);
    }
    
    int pop() {
        if(stdOut.empty())
        {
            while(!stdIn.empty())
            {
                int ans = stdIn.top();
                stdIn.pop();
                stdOut.push(ans);
            }
        }
        int res = stdOut.top();
        stdOut.pop();
        return res;
    }
    
    int peek() {
        int res = this->pop();
        stdOut.push(res);
        return res;

    }
    
    bool empty() {
        return stdIn.empty()&&stdOut.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();
 */

225. 用队列实现栈

可以大家惯性思维,以为还要两个队列来模拟栈,其实只用一个队列就可以模拟栈了。

建议大家掌握一个队列的方法,更简单一些,可以先看视频讲解

题目链接/文章讲解/视频讲解:programmercarl.com/0225.%E7%94…

个人思路: 利用队列来模拟栈的思路,在每次需要弹出元素的时候,需要队列中的最后一个元素,因此需要弹出所有的元素得到最后一个元素,同时弹出的元素需要按照原先的顺序放入队列中。

代码:

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

    }
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        int size = q1.size();
        size--;
        while(size){
            int res = q1.front();
            q1.pop();
            q1.push(res);
            size--;
        }
        int ans = q1.front();
        q1.pop();
        return ans;
    }
    
    int top() {
        return q1.back();
    }
    
    bool empty() {
        return q1.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();
 */