This is really a classic problem, no more word need for this.
class MyQueue {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
stack1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(stack2.empty())
{
while(!stack1.empty())
{
int temp = stack1.pop();
stack2.push(temp);
}
}
stack2.pop();
}
// Get the front element.
public int peek() {
if(stack2.empty())
{
while(!stack1.empty())
{
int temp = stack1.pop();
stack2.push(temp);
}
}
int ans = stack2.pop();
stack2.push(ans);
return ans;
}
// Return whether the queue is empty.
public boolean empty() {
if(stack1.empty()&&stack2.empty())
return true;
else
return false;
}
}