C++ one queue ac solution


  • 0
    F

    class Stack {
    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(void) {
        int len=q.size();
        for (int i=0; i<len-1; i++) {
            int n=q.front();
            q.pop();
            q.push(n);
        }
        q.pop();
    }
    
    // Get the top element.
    int top(void) {
        int len=q.size();
        int n;
        for (int i=0; i<len; i++) {
            n=q.front();
            q.pop();
            q.push(n);
        }
        return n;
    }
    
    // Return whether the stack is empty.
    bool empty(void) {
        return q.empty();
    }
    

    };


Log in to reply
 

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