C++ 0ms solution


  • 0
    J
    class Queue {
        stack<int> myStack, qsRelay, myQueue;
        void updateQueue()
        {
            clear(myQueue); qsRelay = myStack;
            while (!qsRelay.empty())
            {
                myQueue.push(qsRelay.top());
                qsRelay.pop();
            }
        }
        void updateStack()
        {
            clear(myStack); qsRelay = myQueue;
            while (!qsRelay.empty())
            {
                myStack.push(qsRelay.top());
                qsRelay.pop();
            }
        }
        void clear( stack<int> &q )
        {
            stack<int> empty;
            swap( q, empty );
        }
    public:
        // Push element x to the back of queue.
        void push(int x) {
            myStack.push(x);
            updateQueue();
        }
    
        // Removes the element from in front of queue.
        void pop(void) {
            myQueue.pop();
            updateStack();
        }
    
        // Get the front element.
        int peek(void) {
            return myQueue.top();
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return myQueue.empty();
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.