Neat C++ solution using queue::swap()


  • 0
    C

    Personally I think using swap() is a lot better than maintaining empty_q and nonempty_q. I'd like to post this solution so see what people think about using swap()

    class Stack {
    private:
        queue<int> q;
        queue<int> q_tmp;
    public:
        // Push element x onto stack.
        void push(int x) {
            q_tmp.push(x);
            while (!q.empty()) {
                q_tmp.push(q.front());
                q.pop();
            }
            q.swap(q_tmp);
        }
    
        // Removes the element on top of the stack.
        void pop() {
            q.pop();
        }
    
        // Get the top element.
        int top() {
            return q.front();
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return q.empty();
        }
    };

Log in to reply
 

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