day9 栈实现队列

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

    }

};

 

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-09 10:24:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-09 10:24:02       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-09 10:24:02       82 阅读
  4. Python语言-面向对象

    2023-12-09 10:24:02       91 阅读

热门阅读

  1. 华为交换机基本配置

    2023-12-09 10:24:02       58 阅读
  2. mysql怎么优化查询?

    2023-12-09 10:24:02       45 阅读
  3. HTB Devvortex

    2023-12-09 10:24:02       48 阅读
  4. 理解chatGPT的Function calling

    2023-12-09 10:24:02       51 阅读
  5. kafka主题分区副本集群的概念

    2023-12-09 10:24:02       58 阅读