代码随想录算法【Day10】

今日只做一题,剩下的题后面补

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();
        stOut.pop();
        return result;
    }

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

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};
相关推荐
SimonKing5 分钟前
别OCR了,都在用了OXR了,看那看那这款开源的OXR产品
java·后端·程序员
徐小夕11 分钟前
从 RAG 工具到文档处理平台,聊聊 LlamaIndex 为什么成了 AI 应用的标配底座
前端·vue.js·github
map_3d_vis25 分钟前
百度地图视角动画 ViewAnimation:按关键帧做飞行和环绕
前端·webgl·可视化·百度地图·三维
Navigator_Z30 分钟前
LeetCode //C - 1326. Minimum Number of Taps to Open to Water a Garden
c语言·算法·leetcode
Rain的Java大神之路31 分钟前
DTO、VO、PO 到底要不要拆?这场 Java 分层之争,今天一次讲透
java·后端·面试
Moment32 分钟前
怎么给客户讲清本体、知识图谱和大模型的关系
前端·后端·面试
CoderYanger42 分钟前
Java EE 进阶:14.案例综合练习-博客系统(第三弹) :用户登录+强制登录
java·服务器·开发语言·数据库·spring boot·java-ee·mybatis
晓得迷路了1 小时前
栗子前端技术周刊第 156 期 - jQuery 4.1、TanStack Query v6 路线图...
前端·javascript·node.js
恋猫de小郭1 小时前
站起来,Flutter 要支持真正的 3D Texture 了
android·前端·flutter
CoderYanger7 小时前
Java EE 进阶:13. Spring事务和事务传播机制(第二弹)
java·开发语言·数据库·spring boot·后端·spring·java-ee