Simple C++ using two stacks


  • 0
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    class MyQueue {
    public:
        
        /** Push element x to the back of queue. */
        void push(int x) {
            
            // pop from q to aux ( reverse order )
            while ( ! q.empty() ){
                aux.push_back( q.back() );
                q.pop_back();
            }
            aux.push_back(x);
            
            // pop back from aux to q ( forward oreder )
            while ( ! aux.empty() ){
                q.push_back( aux.back() );
                aux.pop_back();
            }
            
        }
        
        /** Removes the element from in front of queue and returns that element. */
        int pop() {
            int result = q.back();
            q.pop_back();
            return result;
        }
        
        /** Get the front element. */
        int peek() {
            return q.back();
        }
        
        /** Returns whether the queue is empty. */
        bool empty() {
            return q.empty();
        }
        
    private:
        vector<int> q; // forward order (queue)
        vector<int> aux; // reverse order
    };
    
    

Log in to reply
 

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