Since the major difference between a queue and a stack is the order(FIF vs LIFO), we know we need to modify peek() and pop() to go in reverse order. We can use our second stack to reverse the order of the elements (by poping s2 and pushing the elements on to s1).
public class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public int size() {
return stack1.size() + stack2.size();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack2.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack1.isEmpty() == true) {
stack2ToStack1();
}
if (stack1.isEmpty() != true) {
return stack1.pop();
} else {
return -1;
}
}
/** Get the front element. */
public int peek() {
if(stack1.isEmpty() == true) {
stack2ToStack1();
}
if (stack1.isEmpty() != true) {
return stack1.peek();
} else {
return -1;
}
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(stack1.isEmpty() == true) {
stack2ToStack1();
}
return stack1.isEmpty();
}
private void stack2ToStack1() {
while (!stack2.empty()) {
stack1.push(stack2.pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/