算法刷题 Day 10 | 232.用栈实现队列 225. 用队列实现栈

今日任务:

  • 理论基础
  • 用栈实现队列
  • 用队列实现栈

理论基础

了解一下 栈与队列的内部实现机智,文中是以C++为例讲解的。

文章讲解:https://programmercarl.com/%E6%A0%88%E4%B8%8E%E9%98%9F%E5%88%97%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html

232.用栈实现队列

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

题目链接/文章讲解/视频讲解:https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html

Tips:这道题难度不大,使用一个输入栈和一个输出栈就行。需要注意的是,如果输出栈没空的话,就不用将输入栈中的内容导入到输出栈里去。

我的题解:

class MyQueue {
public:
    stack<int> stackIn;
    stack<int> stackOut;
    MyQueue() {

    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        if(stackOut.empty()){
            while(!stackIn.empty()){
            stackOut.push(stackIn.top());
            stackIn.pop();
            }
        }

        int result = stackOut.top();
        stackOut.pop();
        return result;
    }
    
    int peek() {
        if(stackOut.empty()){
            while(!stackIn.empty()){
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        int result = stackOut.top();
        return result;
    }
    
    bool empty() {
        if(stackIn.empty() && stackOut.empty()){
            return true;
        }
        else{
            return false;
        }
    }
};

/**
 * 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. 用队列实现栈

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

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

题目链接/文章讲解/视频讲解:https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html

Tips:思路就是将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部

我的题解:

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

    }
    
    void push(int x) {
        que1.push(x);
    }
    
    int pop() {
        for(int i = 0; i < que1.size() - 1;i++){
            que1.push(que1.front());
            que1.pop();
        }
        int result = que1.front();
        que1.pop();
        return result;
    }
    
    int top() {
        int result = pop();
        que1.push(result);
        return result;
    }
    
    bool empty() {
        return que1.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();
 */
posted @ 2023-01-06 23:55  GavinGYM  阅读(38)  评论(0)    收藏  举报