225. Implement Stack using Queues
Problem
Implement a LIFO stack MyStack (push, pop, top, empty) using only queue operations: push to back, peek/pop from front, size and is-empty.
Example: push 1, push 2 → top() = 2, pop() = 2, empty() = false
Constraints: follow-up: use a single queue.
One queue: after pushing x, rotate the previous n−1 elements behind it so x is at the front. Push O(n), pop/top O(1).
Complexity: push O(n), others O(1).
class MyStack:
def __init__(self):
self.q = deque()
def push(self, x: int) -> None:
self.q.append(x)
for _ in range(len(self.q) - 1):
self.q.append(self.q.popleft())
def pop(self) -> int:
return self.q.popleft()
def top(self) -> int:
return self.q[0]
def empty(self) -> bool:
return not self.q
s = MyStack()
s.push(1); s.push(2)
assert s.top() == 2 and s.pop() == 2 and not s.empty() and s.pop() == 1 and s.empty()
s2 = MyStack(); s2.push(5); s2.push(6); s2.push(7)
assert s2.pop() == 7 and s2.top() == 6 and s2.pop() == 6 and s2.top() == 5 and not s2.empty()
class MyStack {
private final Deque<Integer> q = new ArrayDeque<>();
public void push(int x) {
q.addLast(x);
for (int i = 1; i < q.size(); i++) q.addLast(q.pollFirst());
}
public int pop() { return q.pollFirst(); }
public int top() { return q.peekFirst(); }
public boolean empty() { return q.isEmpty(); }
}
type MyStack struct {
q []int // front of the queue = top of the stack
}
func Constructor() MyStack {
return MyStack{}
}
func (this *MyStack) Push(x int) {
this.q = append(this.q, x)
for i := 0; i < len(this.q)-1; i++ { // rotate the new element to the front
this.q = append(this.q[1:], this.q[0])
}
}
func (this *MyStack) Pop() int {
x := this.q[0]
this.q = this.q[1:]
return x
}
func (this *MyStack) Top() int {
return this.q[0]
}
func (this *MyStack) Empty() bool {
return len(this.q) == 0
}