Simple C++ 0ms solution


  • -2
    I

    It's really like the inverse of the "implement a queue using stacks" problem, only with a small twist on the pop...

    class Stack {
    public:
        queue<int> q1;
        queue<int> q2;
    
        // Push element x onto stack.
        void push(int x) {
            // empty q2 into q1, push into q1
            while(!q2.empty()) {
                q1.push(q2.front());
                q2.pop();
            }
            q1.push(x);        
        }
    
        // Removes the element on top of the stack.
        void pop() {
    
             
            // q1 needs to have just one element, so
            
            // empty all from q2 to q1
            while(!q2.empty()) {
                q1.push(q2.front());
                q2.pop();
            }
            
            // empty all bar one from q1 to q2
            while(q1.size()>1) {
                q2.push(q1.front());
                q1.pop();
            }
            
            q1.pop();           
        }
    
        // Get the top element.
        int top() {
             // empty q1 into q2, top is peek front of q2
            while(!q1.empty()) {
                q2.push(q1.front());
                q1.pop();
            }
            return q2.back();          
        }
    
        // Return whether the stack is empty.
        bool empty() {
            // both q1 and q2 are empty
            return q1.empty() && q2.empty();        
        }
    };

  • 0
    Y

    you should not use back on q2.


  • 0
    I

    Why not? The call to back() is returning the correct element - this code passes all the test cases, and it is a valid queue operation. Why shouldn't I use it?


Log in to reply
 

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