Implement Stack using Queues

easy stack queue design

Problem

Implement a LIFO stack using only one FIFO queue. Support push, pop, top, and empty.

Inputpush(1); push(2); top(); pop();
Output2, 2
After push(x), rotate the queue (size-1) times so the new element sits at the front.

from collections import deque
class MyStack:
    def __init__(self): self.q = deque()
    def push(self, x):
        self.q.append(x)
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())
    def pop(self):  return self.q.popleft()
    def top(self):  return self.q[0]
    def empty(self): return not self.q
class MyStack {
  constructor() { this.q = []; }
  push(x) {
    this.q.push(x);
    for (let i = 0; i < this.q.length - 1; i++) this.q.push(this.q.shift());
  }
  pop()  { return this.q.shift(); }
  top()  { return this.q[0]; }
  empty(){ return this.q.length === 0; }
}
class MyStack {
    Deque<Integer> q = new ArrayDeque<>();
    public void push(int x) {
        q.addLast(x);
        for (int i = 0; i < q.size() - 1; i++) q.addLast(q.pollFirst());
    }
    public int pop()  { return q.pollFirst(); }
    public int top()  { return q.peekFirst(); }
    public boolean empty() { return q.isEmpty(); }
}
class MyStack {
    queue<int> q;
public:
    void push(int x) {
        q.push(x);
        for (int i = 0; i < (int)q.size() - 1; i++) { q.push(q.front()); q.pop(); }
    }
    int pop()  { int v = q.front(); q.pop(); return v; }
    int top()  { return q.front(); }
    bool empty() { return q.empty(); }
};
Time: push O(n), others O(1) Space: O(n)