leetcode刷题(第十天)理论基础; 232.用栈实现队列; 225. 用队列实现栈

今日任务 理论基础 232.用栈实现队列 225. 用队列实现栈

卡哥建议:

重点:

参考链接:代码随想录:代码随想录 (programmercarl.com)

补充:

 理论基础

题目讲解(全):代码随想录

题目建议:了解一下 栈与队列的内部实现机制,文中是以C++为例讲解的。

看完代码随想录之后的想法:栈与队列被归类为容器适配器,是STL的两个数据结构。

每日精华:

类似题目:

 232.用栈实现队列

题目讲解(全):代码随想录

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

刷题链接:力扣题目链接

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();//top--首元素
        stOut.pop();
        return result;
    }

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

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};

视频讲解:

栈的基本操作! | LeetCode:232.用栈实现队列 (opens new window)

自己实现过程中遇到哪些困难

每日精华:

类似题目:

225. 用队列实现栈

题目讲解(全):代码随想录

题目建议:可以大家惯性思维,以为还要两个队列来模拟栈,其实只用一个队列就可以模拟栈了。 建议大家掌握一个队列的方法,更简单一些,可以先看视频讲解

刷题链接:力扣题目链接

class MyStack {
public:
    queue<int> que;
    /** Initialize your data structure here. */
    MyStack() {

    }
    /** Push element x onto stack. */
    void push(int x) {
        que.push(x);
    }
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = que.size();
        size--;
        while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front());
            que.pop();
        }
        int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
        que.pop();
        return result;
    }

    /** Get the top element. */
    int top() {
        return que.back();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que.empty();
    }
};

视频讲解:

队列的基本操作! | LeetCode:225. 用队列实现栈 (opens new window)

看到题目的第一思路:

看完代码随想录之后的想法:

自己实现过程中遇到哪些困难

每日精华:

类似题目:

今日收获,记录一下自己的学习时长:

优质文章:学习参考:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值