C++ Single Queue Implementation


  • 4
    M
    class Stack {
    private:
    queue <int> Q;   
    public:
        // Push element x onto stack.
        void push(int x) {
            Q.push(x);
        }
    
        // Removes the element on top of the stack.
        void pop() {
            
            for (int i=0; i<Q.size()-1; i++)
            {
                Q.push(Q.front());
                Q.pop();
            }
            Q.pop(); 
        }
    
        // Get the top element.
        int top() {
            return Q.back();
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return Q.empty();
        }
    };

  • 3
    Z

    Your top function is returning the back of the queue - this breaks queue-like behavior (see the hint "peek/pop from front")!

    Try a similar approach to your pop function, but put it back in after you grab it. Great job otherwise!


Log in to reply
 

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