可以用两个stack实现MyQueue这个类,首先要给这个类添加两个property,即两个stack,同时添加一个构造函数,在这个构造函数中对这两个stack进行初始化。
push(x) -- Push element x to the back of queue:
将元素push到stack2中;
pop() -- Removes the element from in front of queue:
我们使用stack1来pop元素,为此,首先我们要将stack2中的元素以逆序的方式添加到stack1当中去,可以另外写一个函数来实现这个功能。之后在每次pop的时候都先检查stack1是否为空,如果是的话就将stack2的元素全部放入stack1中,否则直接对stack1进行pop
peek() -- Get the front element:
与pop相似,只是将调用的函数变成peek;
empty() -- Return whether the queue is empty:
检查是否stack1和stack2都为空;
代码如下:
class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
// Constructor
MyQueue(){
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void stack2ToStack1(){
while(!stack2.empty()){
stack1.push(stack2.pop());
}
}
// Push element x to the back of queue.
public void push(int x) {
stack2.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(stack1.empty()){
stack2ToStack1();
}
stack1.pop();
}
// Get the front element.
public int peek() {
if(stack1.empty()){
stack2ToStack1();
}
return stack1.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return stack1.empty() && stack2.empty();
}
}