mplement 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 {
private Stack<Integer> a=new Stack<Integer>();
private Stack<Integer> b=new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
a.push(x);
}
// Removes the element from in front of queue.
public void pop() {
peek();
b.pop();
}
// Get the front element.
public int peek() {//这里是整个的重点,取出元素
if(b.empty())
while(!a.empty())
{
b.push(a.pop());
}
return b.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return a.empty()&&b.empty();
}
}
private Stack<Integer> a=new Stack<Integer>();
private Stack<Integer> b=new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
a.push(x);
}
// Removes the element from in front of queue.
public void pop() {
peek();
b.pop();
}
// Get the front element.
public int peek() {//这里是整个的重点,取出元素
if(b.empty())
while(!a.empty())
{
b.push(a.pop());
}
return b.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return a.empty()&&b.empty();
}
}