LeetCode 232. 用栈实现队列

题目描述

使用栈实现队列的下列操作:

  • push(x) – 将一个元素放入队列的尾部。
  • pop() – 从队列首部移除元素。
  • peek() – 返回队列首部的元素。
  • empty() – 返回队列是否为空。

思路

创建两个栈 s1, s2

  1. 入队

    将元素放入 s1 中

  2. 出队

    • 若 s2 为空,将 s1 的元素 放入 s2 中, 此时 s2 的栈顶就是队首元素,s2 栈顶出栈。
    • 若 s2 不为空,直接将 s2 栈顶元素出栈即可。
  3. 获取队首元素

    • 若 s2 不为空,s2 的栈顶元素就是队首元素。
    • 若 s2 为空,s1 不为空,将 s1 中的元素放入 s2 中,然后 s2 的栈顶元素就是队首元素。
class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int> s1, s2;
    int temp;
    int res;
    MyQueue() {

    }

    /** Push element x to the back of queue. */
    void push(int x) {
        s1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(s2.empty())
        {
            while(!s1.empty())
            {
                temp = s1.top();
                s2.push(temp);
                s1.pop();
            }
            res = s2.top();
            s2.pop();
            return res;
        }
        else
        {
            res = s2.top();
            s2.pop();
            return res;
        }
    }

    /** Get the front element. */
    int peek() {
        if(!s2.empty())
        {
            res = s2.top();
            return res;
        }
        else if(!s1.empty())
        {
            while(!s1.empty())
            {
                temp = s1.top();
                s2.push(temp);
                s1.pop();
            }
            res = s2.top();
            return res;
        }
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return s1.empty() && s2.empty();
    }
};
全部评论

相关推荐

我是没经验的毕业生,这啥情况啊会不会是hr在刷kpi
JamesGosli...:字节boss属于是群发了,我都快入职字节了,其他部门还在和我boss打招呼
点赞 评论 收藏
分享
07-09 19:25
门头沟学院 Java
这是要把每一个投校招的都开盒吗?
26届之耻将大局逆转:裁人的时候一次性追回餐费
点赞 评论 收藏
分享
06-07 19:59
门头沟学院 C++
补药卡我啊😭:都快15年前的了还在11新特性
你的简历改到第几版了
点赞 评论 收藏
分享
仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
不亏是提前批,神仙打架,鼠鼠不配了
站队站对牛:现在92都报工艺岗了
投递韶音科技等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务