C++ 0ms solution, any comments or improvements?


  • 0
    U

    Here is my solution:

    class Queue {
    public:
    //Push element x to the back of queue.
    void push(int x) {
    if(_b.size())
    swap(_b, _a);
    _a.push(x);
    }

        // Removes the element from in front of queue.
        void pop(void) {
            if(!empty() && !_b.size())
                swap(_a, _b);
            _b.pop();
        }
    
        // Get the front element.
        int peek(void) {
            if(!empty() && !_b.size())
                swap(_a, _b);
            return _b.top();
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return (!_a.size() && !_b.size());
        }
    
    private:
        void swap(stack<int>& s1, stack<int>& s2)
        {
            while(s1.size())
            {
                s2.push(s1.top());
                s1.pop();
            }
        }
    
    private:
        stack<int> _a;
        stack<int> _b;
    

    };


Log in to reply
 

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