c++ solution using two queues


  • 1
    H
    class Stack {
    public:
        queue<int> q;
        queue<int> tmp;
        // Push element x onto stack.
        void push(int x) {
            while(!q.empty()) {
                tmp.push(q.front());
                q.pop();
            }
            q.push(x);
            while(!tmp.empty()) {
                q.push(tmp.front());
                tmp.pop();
            }
        }
    
        // 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.