前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >LeetCode 232. 用栈实现队列(双栈法->队列)

LeetCode 232. 用栈实现队列(双栈法->队列)

作者头像
Michael阿明
发布2021-02-20 14:39:36
发布2021-02-20 14:39:36
31600
代码可运行
举报
运行总次数:0
代码可运行

1. 题目

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

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/implement-queue-using-stacks 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

类似题目LeetCode 225. 用队列实现栈

2. 解题

代码语言:javascript
代码运行次数:0
复制
class MyQueue {
    stack<int> inSTK;
    stack<int> outSTK;
public:
    /** Initialize your data structure here. */
    MyQueue() { }    
    /** Push element x to the back of queue. */
    void push(int x) {
        inSTK.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    int pop() 
    {
        if(!outSTK.empty())
        {
            int tp = outSTK.top();
            outSTK.pop();
            return tp;
        }
        else
        {
            while(!inSTK.empty())
            {
                outSTK.push(inSTK.top());
                inSTK.pop();
            }
            int tp = outSTK.top();
            outSTK.pop();
            return tp;
        }
    }
    
    /** Get the front element. */
    int peek() {
        if(!outSTK.empty())
            return outSTK.top();
        else
        {
            while(!inSTK.empty())
            {
                outSTK.push(inSTK.top());
                inSTK.pop();
            }
            return outSTK.top();
        }
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return inSTK.empty() && outSTK.empty();
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档