Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
代码如下:
class MyQueue {
Stack<Integer> inbox=new Stack<Integer>();
Stack<Integer> outbox=new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
inbox.push(x);
}
// Removes the element from in front of queue.
public void pop() {
while(!inbox.empty()){
outbox.push(inbox.pop());
}
outbox.pop();
while(!outbox.empty()){
inbox.push(outbox.pop());
}
}
// Get the front element.
public int peek() {
while(!inbox.isEmpty()){
outbox.push(inbox.pop());
}
int temp=outbox.peek();
while(!outbox.isEmpty()){
inbox.push(outbox.pop());
}
return temp;
}
// Return whether the queue is empty.
public boolean empty() {
return inbox.isEmpty();
}
}