Implement Stack using Queues解题报告

Description:

Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Link:

https://leetcode.com/problems/implement-stack-using-queues/#/description

解题方法:

queue::back()可以解决top()函数
每次pop()时都把队伍头部的元素push()进尾部,做size-1次,剩下的第一个元素就是之前队伍尾部的元素。

Time Complexity:

pop() : O(N)
其余:O(1)

完整代码:

class MyStack 
{
private: 
    queue<int> q1;
public:
    /** Push element x onto stack. */
    void push(int x) 
    {
        q1.push(x);
    }
    /** Removes the element on top of the stack and returns that element. */
    int pop() 
    {
        int len = q1.size() - 1;
        while(len--)
        {
            q1.push(q1.front());
            q1.pop();
        }
        int temp = q1.front();
        q1.pop();
        return temp;
    }
    /** Get the top element. */
    int top() 
    {
        return q1.back();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() 
    {
        return q1.empty();
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,793评论 0 33
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,575评论 5 6
  • 叮铃铃,叮铃铃……一阵急促的闹铃声将我从美梦中吵醒,妈妈推开房门进来指了指闹钟对我说:“还不起来,第一天军训就想迟...
    听风入耳阅读 219评论 0 0
  • 今天,我为自己大学四年的文字作序,不是为了将自己四年的生活炫耀给旁人观赏,因为一旦踏出大学的校门,这些经历...
    Glomi阅读 332评论 2 2
  • 我初入华园,初识华园,初明大学,初步大学,都因为我大学的第一堂大课----军训。可能它是我人生中的最后一次军训,而...
    鱼的静时光阅读 549评论 0 19