https://leetcode.com/problems/implement-stack-using-queues/
- Stack
- Queue
- Design
Use a queue and rotate elements on push so the newest element stays at the front.
O(n) per push, O(1) per pop/top
O(n)
import java.util.*;
class MyStack {
private Queue<Integer> queue = new LinkedList<>();
public void push(int x) {
queue.offer(x);
for (int i = 0; i < queue.size() - 1; i++) queue.offer(queue.poll());
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}