C++ code with clear explanation


  • -2
    C
    class Queue {
    public:
    
        // use two stacks a, b
        // push in queue => push in a
        // pop out the queue => if b empty. pop all of a in b, then b.pop()
        //                      else.       b.pop()
        
        // a | | <- top(back)
        //   | |
        //   |-|
        //   | |
        // b | | <- top(front)
    
        // Push element x to the back of queue.
        
        stack<int> a, b;
        
        void move_a2b()
        {
            while( !a.empty() )
            {
                b.push( a.top() );
                a.pop();
            }
        }
        
        void push(int x)
        {
            a.push(x);
        }
    
        // Removes the element from in front of queue.
        void pop(void) 
        {
            if( b.empty() )
                move_a2b();
            if( !b.empty() )
                b.pop();
        }
    
        // Get the front element.
        int peek(void) 
        {
            if( b.empty() )
                move_a2b();
            return b.top();
        }
    
        // Return whether the queue is empty.
        bool empty(void) 
        {
            return a.empty() && b.empty();
        }
    };

Log in to reply
 

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