LeetCode第232题---用栈实现队列
发布日期:2021-05-10 10:38:53 浏览次数:18 分类:精选文章

本文共 2762 字,大约阅读时间需要 9 分钟。

���������������

������������������������������������������������������������������������������������������������������������

  • ���������st1���st2���������������������st1���������������������

  • ���������������st2���������������������������������������st2���������������������st1���������������������������st2���

  • ���������������������������st2���������������������������������������������������������������������st1���������������������������st2���

  • ������������������������������������������������������������������������������������

  • ���������������

    class MyQueue {
    public:
    /** Initialize your data structure here. */
    MyQueue() {}
    /** Push element x to the back of queue. */
    void push(int x) {
    st1.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
    int val;
    while(!st2.empty()) {
    val = st2.top();
    st2.pop();
    return val;
    }
    while(!st1.empty()) {
    val = st1.top();
    st1.pop();
    st2.push(val);
    }
    val = st2.top();
    st2.pop();
    return val;
    }
    /** Get the front element. */
    int peek() {
    int val;
    while(!st2.empty()) {
    val = st2.top();
    return val;
    }
    while(!st1.empty()) {
    val = st1.top();
    st1.pop();
    st2.push(val);
    }
    val = st2.top();
    return val;
    }
    /** Returns whether the queue is empty. */
    bool empty() {
    return st1.empty() && st2.empty();
    }
    private:
    stack
    st1;
    stack
    st2;
    }

    ���������������

    ���������������������������������������������������������������

  • ���������������push������������������������������st1���

  • ���������������pop������

    • ���������������st2������������������������������������������������������������
    • ���������st2������������������st1������������������������������������������st2���������������������st2������������������
  • ���������������������peek������

    • ���������������st2������������������������������������������������������������
    • ���������st2������������������st1������������������������������������������st2���������������st2������������������
  • ���������������������������empty���������������������st1���st2������������������������������������������������������������

  • ������������������������������������������������������������������������������������������peek������������������st2������������st1���������������������������������������������������������������

    上一篇:牛客网---组队竞赛
    下一篇:LeetCode第225题---用队列实现栈

    发表评论

    最新留言

    路过,博主的博客真漂亮。。
    [***.116.15.85]2025年04月05日 02时36分25秒