Share my C++ solution optimized,easy to understand


  • 0
    V
    class Queue {
    public:
        stack<int> s1, s2;
        //if s2 is empty,transfer the elements from stack s1 to stack s2,then these elements are in reversed order in s2
        //peek means get top element in s2(if s2 is empty, call transfer())
        //pop means remove top element in s2(if s2 is empty, call transfer())
        void transfer()
        {
            int x = 0;
            if (s2.empty())
            {
                while (!s1.empty())
                {
                    x= s1.top();
                    s1.pop();
                    s2.push(x);
                }
            }
        }
        
        // Push element x to the back of queue.
        void push(int x) {
            s1.push(x);
        }
        
        // Removes the element from in front of queue.
        void pop(void) {
            transfer();
            s2.pop();
        }
    
        // Get the front element.
        int peek(void) {
            transfer();
            
            return s2.top();
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return s2.empty() && s1.empty();
        }
    };

Log in to reply
 

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