Implement A Queue with Two Stacks

Xavier Carty
2 min readOct 4, 2020

First we create our two stacks. One stack is going to be used to push the data and the other stack is going to be used to pop of the stack.


class MyQueue {
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();

Lets initialize the queue and push the data in stack one

public MyQueue() {

}

/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}

Lets pop off stack two to get that first element from stack one by pushing all of the elements in from stack one into stack two if stack two is empty. If stack2 is not empty that means the element at the top of the stack two has the highest priority.

public int pop() {
if (s2.isEmpty()) {
while (!s1.isEmpty())
s2.push(s1.pop());
}
return s2.pop();
}

if we want to see the element at the top of the stack we can just use stack dot peek method which looks like this;

public int peek() {
if (!s2.isEmpty()) {
return s2.peek();
} else {
while (!s1.isEmpty())
s2.push(s1.pop());
}
return s2.peek();
}

We can just check if the two stacks are empty by

public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}

There you have it, implement a queue with two stacks. Here is the full code.

class MyQueue {
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();
/** Initialize your data structure here. */
public MyQueue() {

}

/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}

/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (s2.isEmpty()) {
while (!s1.isEmpty())
s2.push(s1.pop());
}
return s2.pop();
}

/** Get the front element. */
public int peek() {
if (!s2.isEmpty()) {
return s2.peek();
} else {
while (!s1.isEmpty())
s2.push(s1.pop());
}
return s2.peek();
}

/** Returns whether the queue is empty. */
public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
}

--

--

Xavier Carty

Learning new things everyday and sharing them with them world. Software Engineering , Muay Thai , and Soccer are my passions.