Implementing Stacks Using Queues

Head on over here to try the problem for yourself.

The solution talks about using 2 queues, which frankly I don’t understand :’). I used a single queue to implement this problem.


The goal is to implement a stack using the basic queue features provided such as push(), peek() and pop(). The easiest way to implement this is by inserting elements in reverse order. Then the queue will pop the elements like a stack.


public class MyStack {

  Queue<Integer> q;

  public MyStack() {
    q = new LinkedList<>();

  public void push(int x) {
    for(int i = 0; i < q.size() - 1; i++) {

  public int pop() {
    return q.remove();

  public int top() {
    return q.peek();

  public boolean empty() {
    return q.size() == 0;