Share my C++ solution,easy to understand,but it could be optimized


  • 0
    V
    class Queue {
    public:
        stack<int> s1, s2;
        // 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) {
            int x = 0;
            while (!s1.empty())
            {
                x= s1.top();
                s1.pop();
                s2.push(x);
            }
            s2.pop();
            while(!s2.empty())
            {
                x = s2.top();
                s2.pop();
                s1.push(x);
            }
        }
    
        // Get the front element.
        int peek(void) {
            int x = 0, ret = 0;
            while (!s1.empty())
            {
                x= s1.top();
                s1.pop();
                s2.push(x);
            }
            //s2.pop();
            ret = s2.top();
            while(!s2.empty())
            {
                x = s2.top();
                s2.pop();
                s1.push(x);
            }   
            
            return ret;
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return s1.empty();
        }
    };

Log in to reply
 

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