225. Implement Stack using Queues - cocoder39/coco39_LC GitHub Wiki

225. Implement Stack using Queues

O(1) pop and O(n) push

class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        q.push(x);
        int sz = q.size();
        for (int i = 0; i < sz - 1; i++) {
            int tmp = q.front();
            q.pop();
            q.push(tmp);
        }
    }

    // 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();
    }
private:
    queue<int> q;
};
⚠️ **GitHub.com Fallback** ⚠️