Simple solution with one queue.


  • 0
    G
    class Stack {
    public:
        // Push element x onto stack.
        void push(int x) {
            q.push(x);
            topval = x;
        }
    
        // Removes the element on top of the stack.
        void pop() {
           int tmp = q.front();
           q.pop();
           if(q.size()==1) topval = tmp;
           if(q.size()==0) return;
           pop();
           q.push(tmp);
        }
    
        // Get the top element.
        int top() {
            return topval;
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return q.empty();
        }
    private:
        int topval;
        queue<int> q;
    };

Log in to reply
 

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