美文网首页
Implement Stack using Queues解题报告

Implement Stack using Queues解题报告

作者: 黑山老水 | 来源:发表于2017-07-22 11:26 被阅读21次

    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();
        }
    };
    

    相关文章

      网友评论

          本文标题:Implement Stack using Queues解题报告

          本文链接:https://www.haomeiwen.com/subject/cnxukxtx.html