A 0ms Solution using Two Stacks


  • -2
    Y
    class Queue {
    public:
        // Push element x to the back of queue.
        void push(int x) {
            myQueue.push(x);
        }
    
        // Removes the element from in front of queue.
        void pop(void) {
            int lenq = myQueue.size();
            for(int i = 0; i < lenq - 1; i++) {
                trans.push(myQueue.top());
                myQueue.pop();
            }
            myQueue.pop();
            int lent = trans.size();
            for(int i = 0; i < lent; i++) {
                myQueue.push(trans.top());
                trans.pop();
            }
        }
    
        // Get the front element.
        int peek(void) {
            int lenq = myQueue.size();
            for(int i = 0; i < lenq; i++) {
                trans.push(myQueue.top());
                myQueue.pop();
            }
            int ans = trans.top();
            int lent = trans.size();
            for(int i = 0; i < lent; i++) {
                myQueue.push(trans.top());
                trans.pop();
            }
            return ans;
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return myQueue.empty();
        }
    private:
        stack<int> myQueue,trans;
    };

Log in to reply
 

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