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 inS;
    stack 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解题报告)