这道题得用两个栈去实现
右边的暂且称为in栈,左边的为out栈,进栈操作就是直接进in栈,出栈的话就是把in栈里的元素全部出到out栈,然后再从out进行出栈操作。
class MyQueue {
Stack<Integer> in;
Stack<Integer> out;
/** Initialize your data structure here. */
public MyQueue() {
in =new Stack<>();
out=new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int size=in.size();
if(out.empty()){
for(int i=0;i<size;i++){
int h=in.pop();
out.push(h);
}
}
return out.pop();
}
/** Get the front element. */
public int peek() {
int size=in.size();
if(out.empty()){
for(int i=0;i<size;i++){
int h=in.pop();
out.push(h);
}
}
return out.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return out.empty() && in.empty();
}
}