美文网首页
Implement Queue using Stacks解题报告

Implement Queue using Stacks解题报告

作者: 黑山老水 | 来源:发表于2017-07-20 06:36 被阅读7次

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

相关文章

网友评论

      本文标题:Implement Queue using Stacks解题报告

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