Implement Queue using Stacks解题报告

Description:

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.

Link:

https://leetcode.com/problems/implement-queue-using-stacks/#/description

解题方法:

用两个栈in和out来解决,当调用函数pop()peek()时,当out为空时,把in栈的元素压到out里面去,然后对out进行pop()top()的调用。

Time Complexity:

pop()peek():O(1)到 O(N)

完整代码:

class MyQueue 
{
private:
    stack<int> inS;
    stack<int> outS;
    void inToOut()
    {
        while(!inS.empty())
        {
            outS.push(inS.top());
            inS.pop();
        }
    }
public:
    /** Push element x to the back of queue. */
    void push(int x) 
    {
        inS.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() 
    {
        if(outS.empty())
            inToOut();
        int front = outS.top();
        outS.pop();
        return front;
    }
    
    /** Get the front element. */
    int peek() 
    {
        if(outS.empty())
            inToOut();
        return outS.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() 
    {
        return inS.empty() && outS.empty();
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,358评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,543评论 0 23
  • 如果人生是一幅美丽的画卷,军训就是画卷上最鲜艳的色彩;如果人生是大海,军训就是大海中的灯塔。军训就像一杯浓郁而久远...
    083阅读 1,414评论 0 0
  • 啼 破天 见新欢 风流少年 侧帽为扬鞭 初遇亭亭展颜、 星光璀璨落眉间 雪月夜依偎不觉寒 风兮云兮骤变似转眼 流年...
    侠女小艾阅读 2,767评论 0 0
  • 一个像狮子宝宝那么小的石头 迷路了 它一定是在打僵尸的时候 转了一圈 看不到妈妈 把僵尸给打倒了 才迷路的吧 一个...
    小雅鹿鸣阅读 1,621评论 0 0

友情链接更多精彩内容